E-commerce REST
A extendable-ready, modular REST API for e-commerce platforms with JWT authentication, product management, order workflows, and Razorpay integration.
Overview
A full-stack ready e-commerce backend built on Express and MongoDB. Implements authentication, product catalog management, order processing, and Razorpay payment verification. Follows clean MVC patterns with dedicated models, controllers, routes, and middleware. Designed for reuse across storefronts, admin dashboards, or mobile commerce apps.
Installation
What This Does
Installs a complete e-commerce backend foundation with authentication, product CRUD, order flow, Razorpay integration, and secure middleware.
Files & Folders Created
| File / Path | Description |
|---|---|
| /src/models/userModel.js | User schema with hashed passwords. |
| /src/models/productModel.js | Product schema with categories, images, stock. |
| /src/models/orderModel.js | Order, order items, status, payment metadata. |
| /src/controllers/authController.js | Register, login, profile logic. |
| /src/controllers/productController.js | Product search, CRUD, pagination. |
| /src/controllers/orderController.js | Order creation, Razorpay order, payment verification. |
| /src/routes/authRoutes.js | User auth endpoints. |
| /src/routes/productRoutes.js | Public + admin product operations. |
| /src/routes/orderRoutes.js | Order/checkout/payment APIs. |
| /src/middleware/authMiddleware.js | JWT verification + admin guard. |
| /src/middleware/errorMiddleware.js | Centralized error formatting. |
| /src/config/db.js | MongoDB connection. |
| /src/config/razorpay.js | Razorpay instance. |
| /src/utils/generateToken.js | Helper for JWT access tokens. |
| server.js | Main Express bootstrap with security middleware. |
Files to be modified
| File / Path | Description |
|---|---|
| .env | Adds JWT secret, MongoDB URI, Razorpay keys, rate limits. |
| package.json | Adds required production dependencies. |
Configuration
# Database MONGODB_URI=mongodb://localhost:27017/backternity-ecom # Server PORT=3001 NODE_ENV=development # JWT JWT_SECRET=your_32_char_or_longer_secret JWT_EXPIRES_IN=7d # Razorpay RAZORPAY_KEY_ID=your_razorpay_key_id RAZORPAY_KEY_SECRET=your_razorpay_key_secret # Misc API_PREFIX=/api/v1 RATE_LIMIT_WINDOW_MS=60000 RATE_LIMIT_MAX=100
Frontend Integration
These endpoints allow seamless integration with any storefront—Next.js, React, Vue, mobile apps, or server-side frameworks. A typical frontend workflow includes user authentication, product listing, and Razorpay checkout.
Registers a new user account.
Authenticates user credentials and returns JWT token.
Fetches products with search, filtering, and pagination.
Creates an order and a corresponding Razorpay order on the server.
Verifies the Razorpay signature and marks the order as paid.
Example
1// Example React flow for Razorpay Checkout
2import { useState } from 'react';
3
4export default function CheckoutButton() {
5 const [loading, setLoading] = useState(false);
6
7 async function createOrder() {
8 setLoading(true);
9
10 // Step 1: Create server order
11 const res = await fetch('/api/v1/orders', {
12 method: 'POST',
13 headers: { 'Content-Type': 'application/json',
14 Authorization: 'Bearer ' + localStorage.getItem('token') },
15 body: JSON.stringify({
16 orderItems: [...],
17 shippingAddress: {...},
18 paymentMethod: 'razorpay',
19 totalPrice: 1200
20 })
21 });
22
23 const data = await res.json();
24
25 // Step 2: Open Razorpay checkout
26 const rzp = new window.Razorpay({
27 key: data.razorpay.key,
28 amount: data.razorpay.amount,
29 currency: 'INR',
30 order_id: data.razorpay.id,
31 handler: async function (paymentResponse) {
32 // Step 3: Verify payment
33 await fetch('/api/v1/orders/' + data.orderId + '/payment/verify', {
34 method: 'POST',
35 headers: { 'Content-Type': 'application/json',
36 Authorization: 'Bearer ' + localStorage.getItem('token') },
37 body: JSON.stringify(paymentResponse)
38 });
39 }
40 });
41
42 rzp.open();
43 setLoading(false);
44 }
45
46 return (
47 <button onClick={createOrder} disabled={loading}>
48 {loading ? 'Processing…' : 'Checkout with Razorpay'}
49 </button>
50 );
51}Usage
1// Protect admin routes
2const express = require('express');
3const { protect, admin } = require('./src/middleware/authMiddleware');
4
5const router = express.Router();
6
7router.post('/products', protect, admin, (req, res) => {
8 res.json({ message: 'Admin access granted' });
9});