Skip to content

Production-ready e-commerce REST API with JWT authentication, product/order management, Cloudinary image uploads, role-based access control, and admin analytics built on Node.js, Express, and MongoDB.

License

Notifications You must be signed in to change notification settings

MinaMalakH/Ecommerce-Backend-API

Repository files navigation

E-Commerce Backend API

Modern, secure, and scalable RESTful API built for e-commerce applications using Node.js, Express, MongoDB, and modern best practices.

✨ Features

  • Secure Authentication

    • JWT Access + Refresh Token rotation
    • Email verification with secure hashed tokens
    • Password change with session invalidation
    • Role-based authorization (User / Admin)
  • Product Management

    • CRUD operations (Admin only)
    • Cloudinary image upload with size/format validation
    • Advanced search, filtering, pagination & text search
    • Discount price support
  • Category Management (nested categories support)

  • Order System

    • Create orders with real-time stock deduction
    • Multiple payment methods (COD + Card placeholder)
    • Order status management (Admin)
    • User order history
  • Reviews & Ratings

    • Prevent duplicate reviews
    • Automatic average rating & review count calculation
  • Admin Dashboard Analytics

    • Overview stats (users, products, orders, revenue)
    • Orders by status
    • Monthly revenue breakdown
    • Top selling products
  • Developer Experience

    • Joi validation middleware
    • Global error handling & 404
    • Environment-based email (Ethereal for dev, Gmail for prod)
    • Clean MVC-like architecture (Controllers / Services / Models)
    • Comprehensive logging & health check endpoint

πŸ›  Tech Stack

  • Runtime: Node.js + Express
  • Database: MongoDB (Mongoose)
  • Authentication: JWT + Refresh Tokens
  • Image Storage: Cloudinary + Multer
  • Email: Nodemailer (Ethereal dev / Gmail prod)
  • Validation: Joi
  • Security: bcrypt, helmet (recommended), rate limiting (recommended)
  • Other: slugify, crypto, aggregation pipelines

πŸ“ Project Structure

.
β”œβ”€β”€ app.js                          # Application entry point
β”œβ”€β”€ package.json                    # Project dependencies
β”œβ”€β”€ README.md                       # Project documentation
β”œβ”€β”€ LICENSE                         # MIT License
β”œβ”€β”€ .env.example                    # Environment variables template
β”œβ”€β”€ Ecommerce-Backend-API.postman_collection.json  # Postman collection
└── src/
    β”œβ”€β”€ config/                     # Configuration files
    β”‚   β”œβ”€β”€ cloudinary.js           # Cloudinary setup
    β”‚   β”œβ”€β”€ DB.js                   # MongoDB connection
    β”‚   └── nodemailer.js           # Email configuration
    β”œβ”€β”€ controllers/                # Route handlers & business logic
    β”‚   β”œβ”€β”€ admin.controller.js     # Admin analytics endpoints
    β”‚   β”œβ”€β”€ auth.controller.js      # Authentication logic
    β”‚   β”œβ”€β”€ category.controller.js  # Category operations
    β”‚   β”œβ”€β”€ order.controller.js     # Order management
    β”‚   β”œβ”€β”€ product.controller.js   # Product operations
    β”‚   └── review.controller.js    # Review operations
    β”œβ”€β”€ middlewares/                # Express middlewares
    β”‚   β”œβ”€β”€ auth.middleware.js      # JWT authentication
    β”‚   β”œβ”€β”€ role.middleware.js      # Role-based access control
    β”‚   β”œβ”€β”€ upload.middleware.js    # Image upload handling
    β”‚   └── validation.js           # Request validation
    β”œβ”€β”€ models/                     # Database schemas (Mongoose)
    β”‚   β”œβ”€β”€ Category.js
    β”‚   β”œβ”€β”€ Order.js
    β”‚   β”œβ”€β”€ Product.js
    β”‚   β”œβ”€β”€ RefreshToken.js
    β”‚   β”œβ”€β”€ Review.js
    β”‚   └── User.js
    β”œβ”€β”€ routes/                     # API route definitions
    β”‚   β”œβ”€β”€ admin.routes.js
    β”‚   β”œβ”€β”€ auth.routes.js
    β”‚   β”œβ”€β”€ category.routes.js
    β”‚   β”œβ”€β”€ order.routes.js
    β”‚   β”œβ”€β”€ product.routes.js
    β”‚   └── review.routes.js
    β”œβ”€β”€ services/                   # Business logic & database operations
    β”‚   β”œβ”€β”€ admin.service.js
    β”‚   β”œβ”€β”€ auth.service.js
    β”‚   β”œβ”€β”€ category.service.js
    β”‚   β”œβ”€β”€ email.service.js
    β”‚   β”œβ”€β”€ order.service.js
    β”‚   β”œβ”€β”€ product.service.js
    β”‚   └── review.service.js
    β”œβ”€β”€ utils/                      # Utility functions
    β”‚   β”œβ”€β”€ emailsTemplates.js      # Email HTML templates
    β”‚   └── tokens.js               # Token generation utilities
    └── validator/                  # Request validation schemas
        └── auth.validator.js       # Joi validation schemas

πŸš€ Quick Start

Prerequisites

  • Node.js β‰₯ 18
  • MongoDB (local or Atlas)
  • Cloudinary account
  • Gmail (for production emails β€” use App Password)

Installation

# Clone the repository
git clone https://github.com/MinaMalakH/Ecommerce-Backend-API.git
cd Ecommerce-Backend-API

# Install dependencies
npm install

# Create .env file (use .env.example as template)
cp .env.example .env

# Fill in your environment variables
# Important ones:
# MONGODB_URI
# JWT_ACCESS_SECRET
# JWT_REFRESH_SECRET
# CLOUDINARY_CLOUD_NAME / API_KEY / API_SECRET
# EMAIL_USER / EMAIL_PASS (for production)
# FRONTEND_URL

# Start development server
npm run dev

πŸ“š API Endpoints

Base URL: http://localhost:5000/api

Health Check

Method Endpoint Description Auth
GET /health Server health check ❌

Authentication

Method Endpoint Description Auth
POST /auth/register Register new user ❌
POST /auth/login Login user ❌
POST /auth/refresh Refresh access token ❌
POST /auth/logout Logout user βœ…
GET /auth/verify-email Verify email with token ❌
GET /auth/resend-verification Resend verification email ❌
GET /auth/me Get current user profile βœ…
PATCH /auth/change-password Change user password βœ…

Categories

Method Endpoint Description Auth Role
POST /category Create category βœ… Admin
GET /category Get all categories ❌ -
GET /category/:id Get category by ID ❌ -
PATCH /category/:id Update category βœ… Admin
DELETE /category/:id Delete category βœ… Admin

Products

Method Endpoint Description Auth Role
POST /product Create product (with image) βœ… Admin
GET /product Get all products (paginated, searchable) ❌ -
GET /product/:id Get product by ID ❌ -
PATCH /product/:id Update product βœ… Admin
DELETE /product/:id Delete product βœ… Admin

Query Parameters for GET /product:

  • page - Page number (default: 1)
  • limit - Items per page (default: 10)
  • search - Search by name or description

Orders

Method Endpoint Description Auth Role
POST /order Create order βœ… User
GET /order/me Get user's orders βœ… User
GET /order Get all orders βœ… Admin
PATCH /order/:id Update order status βœ… Admin

Reviews

Method Endpoint Description Auth Role
POST /review/:productId Create/update product review βœ… User

Admin Analytics

Method Endpoint Description Auth Role
GET /admin/analytics/overview Get overview stats (users, products, orders, revenue) βœ… Admin
GET /admin/analytics/order-by-status Get orders grouped by status βœ… Admin
GET /admin/analytics/monthly-revenue Get monthly revenue breakdown βœ… Admin
GET /admin/analytics/top-products Get top selling products βœ… Admin

Legend:

  • βœ… = Requires authentication
  • ❌ = Public endpoint

πŸ“€ Postman Collection

A complete Postman collection is included: Ecommerce-Backend-API.postman_collection.json

How to Import:

  1. Open Postman
  2. Click Import β†’ Upload Files (or drag & drop)
  3. Select Ecommerce-Backend-API.postman_collection.json
  4. Set environment variables:
    • base_url = http://localhost:5000 (or your API URL)
    • access_token = Your JWT token (obtained after login)

πŸ“ Environment Variables

Create a .env file in the root directory (see .env.example):

# Server
NODE_ENV=development
PORT=5000

# Database
MONGODB_URI=mongodb://localhost:27017/ecommerce

# JWT
JWT_ACCESS_SECRET=your_access_secret_key_here
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_SECRET=your_refresh_secret_key_here
JWT_REFRESH_EXPIRY=7d

# Cloudinary
CLOUDINARY_CLOUD_NAME=your_cloudinary_name
CLOUDINARY_API_KEY=your_cloudinary_key
CLOUDINARY_API_SECRET=your_cloudinary_secret

# Email (Development - Ethereal)
EMAIL_SERVICE=gmail
EMAIL_USER=your_gmail@gmail.com
EMAIL_PASS=your_app_password

# Frontend
FRONTEND_URL=http://localhost:3000

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘€ Author

Mina Malak

🀝 Contributing

Contributions are welcome! Feel free to open issues or submit pull requests.

⭐ Show Your Support

If you found this project helpful, please give it a ⭐ on GitHub!

About

Production-ready e-commerce REST API with JWT authentication, product/order management, Cloudinary image uploads, role-based access control, and admin analytics built on Node.js, Express, and MongoDB.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published