Multi-Vendor eCommerce API

A complete Node.js Express backend for a multi-vendor eCommerce platform

Features

User Management

Signup, login, and JWT-based authentication for customers and vendors

Vendor System

Vendor registration, profile management, and product upload

Product CRUD

Complete product management with vendor references

Project Setup

1. Initialize Project

mkdir multi-vendor-ecommerce
cd multi-vendor-ecommerce
npm init -y

2. Install Dependencies

npm install express mongoose bcryptjs jsonwebtoken express-validator dotenv cors multer

3. Project Structure

multi-vendor-ecommerce/
├── config/ # Configuration files
│ └── db.js # Database connection
├── controllers/ # Route controllers
│ ├── auth.js
│ ├── products.js
│ └── vendors.js
├── middleware/ # Custom middleware
│ ├── auth.js
│ └── error.js
├── models/ # Mongoose models
│ ├── Product.js
│ ├── User.js
│ └── Vendor.js
├── routes/ # API routes
│ ├── auth.js
│ ├── products.js
│ └── vendors.js
├── uploads/ # Product images
├── utils/ # Utility functions
│ └── upload.js # File upload helper
├── .env # Environment variables
└── server.js # Main application file

Mongoose Models

1. User Model (models/User.js)

const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const UserSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please add a name'] }, email: { type: String, required: [true, 'Please add an email'], unique: true, match: [ /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please add a valid email' ] }, role: { type: String, enum: ['customer', 'vendor', 'admin'], default: 'customer' }, password: { type: String, required: [true, 'Please add a password'], minlength: 6, select: false }, resetPasswordToken: String, resetPasswordExpire: Date, createdAt: { type: Date, default: Date.now } }); // Encrypt password using bcrypt UserSchema.pre('save', async function(next) { if (!this.isModified('password')) { next(); } const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); }); // Sign JWT and return UserSchema.methods.getSignedJwtToken = function() { return jwt.sign({ id: this._id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE }); }; // Match user entered password to hashed password in database UserSchema.methods.matchPassword = async function(enteredPassword) { return await bcrypt.compare(enteredPassword, this.password); }; module.exports = mongoose.model('User', UserSchema);

2. Vendor Model (models/Vendor.js)

const mongoose = require('mongoose'); const VendorSchema = new mongoose.Schema({ user: { type: mongoose.Schema.ObjectId, ref: 'User', required: true, unique: true }, storeName: { type: String, required: [true, 'Please add a store name'], unique: true, trim: true, maxlength: [50, 'Store name cannot be more than 50 characters'] }, description: { type: String, required: [true, 'Please add a description'], maxlength: [500, 'Description cannot be more than 500 characters'] }, address: { type: String, required: [true, 'Please add an address'] }, phone: { type: String, required: [true, 'Please add a phone number'], maxlength: [20, 'Phone number cannot be longer than 20 characters'] }, website: { type: String, match: [ /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/, 'Please use a valid URL with HTTP or HTTPS' ] }, rating: { type: Number, min: [1, 'Rating must be at least 1'], max: [5, 'Rating must can not be more than 5'] }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Vendor', VendorSchema);

3. Product Model (models/Product.js)

const mongoose = require('mongoose'); const ProductSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please add a product name'], trim: true, maxlength: [100, 'Product name cannot be more than 100 characters'] }, description: { type: String, required: [true, 'Please add a description'], maxlength: [1000, 'Description cannot be more than 1000 characters'] }, price: { type: Number, required: [true, 'Please add a price'], min: [0, 'Price must be at least 0'] }, category: { type: String, required: [true, 'Please add a category'], enum: [ 'Electronics', 'Clothing', 'Home', 'Books', 'Beauty', 'Sports', 'Other' ] }, stock: { type: Number, required: [true, 'Please add stock quantity'], min: [0, 'Stock cannot be less than 0'] }, images: { type: [String], default: [] }, vendor: { type: mongoose.Schema.ObjectId, ref: 'Vendor', required: true }, rating: { type: Number, min: [1, 'Rating must be at least 1'], max: [5, 'Rating must can not be more than 5'], default: 1 }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Product', ProductSchema);

API Routes

1. Authentication Routes (routes/auth.js)

POST /api/v1/auth/register

Register a new user (customer or vendor)

// Request Body { "name": "John Doe", "email": "john@example.com", "password": "123456", "role": "customer" // or "vendor" }
POST /api/v1/auth/login

Login user and get JWT token

// Request Body { "email": "john@example.com", "password": "123456" }
GET /api/v1/auth/me

Get currently logged in user (requires authentication)

2. Vendor Routes (routes/vendors.js)

POST /api/v1/vendors

Register as a vendor (requires user to be logged in)

// Request Body { "storeName": "Awesome Store", "description": "We sell awesome products", "address": "123 Main St, City", "phone": "1234567890", "website": "https://awesomestore.com" }
GET /api/v1/vendors

Get all vendors (public)

GET /api/v1/vendors/:id

Get single vendor (public)

PUT /api/v1/vendors/:id

Update vendor profile (requires vendor ownership or admin role)

3. Product Routes (routes/products.js)

GET /api/v1/products

Get all products (public, with filtering, pagination)

// Query Parameters ?category=Electronics&price[lte]=1000&sort=-price&limit=10&page=1
GET /api/v1/products/:id

Get single product (public)

POST /api/v1/products

Create new product (requires vendor role)

// Request Body (multipart/form-data) { "name": "Smartphone", "description": "Latest smartphone", "price": 999.99, "category": "Electronics", "stock": 100, "images": [file1, file2] // Uploaded files }
PUT /api/v1/products/:id

Update product (requires vendor ownership or admin role)

DELETE /api/v1/products/:id

Delete product (requires vendor ownership or admin role)

Middleware

1. Authentication Middleware (middleware/auth.js)

const jwt = require('jsonwebtoken'); const ErrorResponse = require('../utils/errorResponse'); const User = require('../models/User'); // Protect routes exports.protect = async (req, res, next) => { let token; if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { token = req.headers.authorization.split(' ')[1]; } // Make sure token exists if (!token) { return next(new ErrorResponse('Not authorized to access this route', 401)); } try { // Verify token const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded.id); next(); } catch (err) { return next(new ErrorResponse('Not authorized to access this route', 401)); } }; // Grant access to specific roles exports.authorize = (...roles) => { return (req, res, next) => { if (!roles.includes(req.user.role)) { return next( new ErrorResponse(`User role ${req.user.role} is not authorized to access this route`, 403) ); } next(); }; };

2. Error Handling Middleware (middleware/error.js)

const ErrorResponse = require('../utils/errorResponse'); const errorHandler = (err, req, res, next) => { let error = { ...err }; error.message = err.message; // Log to console for dev console.log(err); // Mongoose bad ObjectId if (err.name === 'CastError') { const message = `Resource not found with id of ${err.value}`; error = new ErrorResponse(message, 404); } // Mongoose duplicate key if (err.code === 11000) { const message = 'Duplicate field value entered'; error = new ErrorResponse(message, 400); } // Mongoose validation error if (err.name === 'ValidationError') { const message = Object.values(err.errors).map(val => val.message); error = new ErrorResponse(message, 400); } res.status(error.statusCode || 500).json({ success: false, error: error.message || 'Server Error' }); }; module.exports = errorHandler;

3. File Upload Middleware (utils/upload.js)

const multer = require('multer'); const path = require('path'); const fs = require('fs'); // Ensure uploads directory exists const uploadDir = path.join(__dirname, '../uploads'); if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir, { recursive: true }); } // Set up storage for uploaded files const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, uploadDir); }, filename: function(req, file, cb) { cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`); } }); // File filter for images only const fileFilter = (req, file, cb) => { const filetypes = /jpe?g|png|webp/; const mimetypes = /image\/jpe?g|image\/png|image\/webp/; const extname = filetypes.test(path.extname(file.originalname).toLowerCase()); const mimetype = mimetypes.test(file.mimetype); if (extname && mimetype) { cb(null, true); } else { cb(new Error('Images only!'), false); } }; const upload = multer({ storage, fileFilter, limits: { fileSize: 5 * 1024 * 1024 } // 5MB limit }); // Custom middleware for handling multiple image uploads exports.uploadProductImages = upload.array('images', 5); // Max 5 images // Middleware to process uploaded files exports.processImages = (req, res, next) => { if (!req.files || req.files.length === 0) { return next(); } req.body.images = req.files.map(file => `/uploads/${file.filename}`); next(); };

Environment Configuration

.env File

NODE_ENV=development
PORT=5000
MONGO_URI=mongodb://localhost:27017/multi-vendor-ecommerce
JWT_SECRET=your_jwt_secret
JWT_EXPIRE=30d
JWT_COOKIE_EXPIRE=30

Database Configuration (config/db.js)

const mongoose = require('mongoose'); const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }); console.log(`MongoDB Connected: ${conn.connection.host}`); } catch (err) { console.error(err); process.exit(1); } }; module.exports = connectDB;

Main Server File (server.js)

const express = require('express'); const dotenv = require('dotenv'); const morgan = require('morgan'); const colors = require('colors'); const fileupload = require('express-fileupload'); const cookieParser = require('cookie-parser'); const mongoSanitize = require('express-mongo-sanitize'); const helmet = require('helmet'); const xss = require('xss-clean'); const rateLimit = require('express-rate-limit'); const hpp = require('hpp'); const cors = require('cors'); const errorHandler = require('./middleware/error'); const connectDB = require('./config/db'); // Load env vars dotenv.config({ path: './config/config.env' }); // Connect to database connectDB(); // Route files const auth = require('./routes/auth'); const vendors = require('./routes/vendors'); const products = require('./routes/products'); const app = express(); // Body parser app.use(express.json()); // Cookie parser app.use(cookieParser()); // Dev logging middleware if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } // File uploading app.use(fileupload()); // Sanitize data app.use(mongoSanitize()); // Set security headers app.use(helmet()); // Prevent XSS attacks app.use(xss()); // Rate limiting const limiter = rateLimit({ windowMs: 10 * 60 * 1000, // 10 mins max: 100 }); app.use(limiter); // Prevent http param pollution app.use(hpp()); // Enable CORS app.use(cors()); // Set static folder app.use(express.static(path.join(__dirname, 'public'))); // Mount routers app.use('/api/v1/auth', auth); app.use('/api/v1/vendors', vendors); app.use('/api/v1/products', products); app.use(errorHandler); const PORT = process.env.PORT || 5000; const server = app.listen( PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold) ); // Handle unhandled promise rejections process.on('unhandledRejection', (err, promise) => { console.log(`Error: ${err.message}`.red); // Close server & exit process server.close(() => process.exit(1)); });

Made with DeepSite LogoDeepSite - 🧬 Remix