Skip to content

πŸ›’ A complete RESTful API for e-commerce applications built with Node.js, Express, and MongoDB. Features secure JWT authentication, product management, user profiles, review system, and order processing with comprehensive security measures.

Notifications You must be signed in to change notification settings

CodingWithSanjeet/ecommerce-rest-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›’ E-Commerce API

A robust and feature-rich RESTful API for e-commerce applications built with Node.js, Express, and MongoDB.

Node.js Express.js MongoDB JWT

Live Demo API Status

🌐 Live Demo

πŸš€ Live API - Experience the API in action

πŸ“– API Documentation - Interactive documentation and testing interface

πŸ“„ Postman Collection - Ready-to-use Postman collection

Quick Test

Try the API instantly:

# Get all products
curl https://ecommerce-rest-api-bmw6.onrender.com/api/v1/products

# Register a new user
curl -X POST  https://ecommerce-rest-api-bmw6.onrender.com/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"name":"Test User","email":"test@example.com","password":"password123"}'

✨ Features

  • πŸ” Authentication & Authorization - JWT-based auth with secure cookie handling
  • πŸ‘₯ User Management - Registration, login, profile management, and role-based access
  • πŸ“¦ Product Management - CRUD operations for products with image upload
  • ⭐ Review System - Users can rate and review products
  • πŸ›οΈ Order Processing - Complete order management with status tracking
  • πŸ”’ Security - Rate limiting, XSS protection, MongoDB injection prevention
  • πŸ“ File Upload - Secure image upload for product images
  • πŸ“Š Data Validation - Comprehensive input validation with Joi
  • πŸ”„ Error Handling - Centralized error handling with custom error classes

πŸš€ Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Database: MongoDB with Mongoose ODM
  • Authentication: JSON Web Tokens (JWT)
  • Validation: Joi
  • Security: Helmet, CORS, XSS Protection, Rate Limiting
  • File Upload: Express File Upload
  • Email: Nodemailer
  • Development: Nodemon

πŸ“‹ Prerequisites

Before running this project, make sure you have the following installed:

  • Node.js (v14 or higher)
  • MongoDB (local or cloud instance)
  • npm or yarn

⚑ Quick Start

πŸ’‘ Want to test immediately? Check out our live demo or download the Postman collection

1. Clone the repository

git clone https://github.com/CodingWithSanjeet/ecommerce-rest-api.git
cd ecommerce-rest-api

2. Install dependencies

npm install

3. Environment Setup

Create a .env file in the root directory:

# Database
MONGO_URI=mongodb://localhost:27017/ecom-api

# JWT
JWT_SECRET=your-super-secret-jwt-key
JWT_LIFETIME=30d

# Server
PORT=3000
NODE_ENV=development

# Email Configuration (Optional)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password

4. Start the development server

npm start

The API will be running at http://localhost:3000


πŸ“š API Documentation

Base URL

Local Development:

http://localhost:3000/api/v1

Live Production:

https://your-app-name.onrender.com/api/v1

πŸ” Authentication Endpoints

Method Endpoint Description
POST /auth/register Register a new user
POST /auth/login Login user
POST /auth/logout Logout user
POST /auth/forgot-password Request password reset
POST /auth/reset-password Reset password

πŸ‘₯ User Endpoints

Method Endpoint Description Auth Required
GET /users Get all users (Admin only) βœ…
GET /users/profile Get current user profile βœ…
PATCH /users/profile Update user profile βœ…
PATCH /users/change-password Change password βœ…

πŸ“¦ Product Endpoints

Method Endpoint Description Auth Required
GET /products Get all products ❌
GET /products/:id Get single product ❌
POST /products Create product (Admin only) βœ…
PATCH /products/:id Update product (Admin only) βœ…
DELETE /products/:id Delete product (Admin only) βœ…
POST /products/upload-image Upload product image βœ…

⭐ Review Endpoints

Method Endpoint Description Auth Required
GET /reviews Get all reviews ❌
GET /reviews/:id Get single review ❌
POST /reviews Create review βœ…
PATCH /reviews/:id Update review (Owner only) βœ…
DELETE /reviews/:id Delete review (Owner only) βœ…

πŸ›οΈ Order Endpoints

Method Endpoint Description Auth Required
GET /orders Get all orders (Admin only) βœ…
GET /orders/my-orders Get current user orders βœ…
GET /orders/:id Get single order βœ…
POST /orders Create order βœ…
PATCH /orders/:id Update order βœ…

πŸ“ Request Examples

Register User

POST /api/v1/auth/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123"
}

Create Product

POST /api/v1/products
Authorization: Bearer <your-jwt-token>
Content-Type: application/json

{
  "name": "Wireless Headphones",
  "price": 99.99,
  "description": "High-quality wireless headphones",
  "category": "electronics",
  "company": "techcorp",
  "colors": ["black", "white"],
  "featured": true,
  "freeShipping": true,
  "inventory": 50
}

Create Order

POST /api/v1/orders
Authorization: Bearer <your-jwt-token>
Content-Type: application/json

{
  "tax": 8.99,
  "shippingFee": 5.99,
  "orderItems": [
    {
      "name": "Wireless Headphones",
      "image": "/uploads/headphones.jpg",
      "price": 99.99,
      "amount": 2,
      "product": "64f8a9b2c1d2e3f4a5b6c7d8"
    }
  ]
}

πŸ“ Project Structure

ecom-api/
β”œβ”€β”€ controller/          # Route controllers
β”‚   β”œβ”€β”€ authController.js
β”‚   β”œβ”€β”€ userController.js
β”‚   β”œβ”€β”€ productController.js
β”‚   β”œβ”€β”€ reviewController.js
β”‚   └── orderController.js
β”œβ”€β”€ models/              # Mongoose models
β”‚   β”œβ”€β”€ User.js
β”‚   β”œβ”€β”€ Product.js
β”‚   β”œβ”€β”€ Review.js
β”‚   └── Order.js
β”œβ”€β”€ routes/              # API routes
β”‚   β”œβ”€β”€ authRoutes.js
β”‚   β”œβ”€β”€ userRoutes.js
β”‚   β”œβ”€β”€ productRoutes.js
β”‚   β”œβ”€β”€ reviewRoutes.js
β”‚   └── orderRoutes.js
β”œβ”€β”€ middleware/          # Custom middleware
β”‚   β”œβ”€β”€ authentication.js
β”‚   β”œβ”€β”€ error-handler.js
β”‚   └── not-found.js
β”œβ”€β”€ errors/              # Custom error classes
β”‚   β”œβ”€β”€ AppError.js
β”‚   β”œβ”€β”€ BadRequestError.js
β”‚   β”œβ”€β”€ NotFoundError.js
β”‚   β”œβ”€β”€ UnauthenticatedError.js
β”‚   └── UnauthorizedError.js
β”œβ”€β”€ utils/               # Utility functions
β”‚   β”œβ”€β”€ asyncWrapper.js
β”‚   β”œβ”€β”€ jwt.js
β”‚   └── index.js
β”œβ”€β”€ db/                  # Database connection
β”‚   └── connect.js
β”œβ”€β”€ public/              # Static files
β”‚   └── uploads/         # Uploaded images
β”œβ”€β”€ app.js               # App configuration
β”œβ”€β”€ package.json
└── README.md

πŸ”’ Security Features

  • Rate Limiting: Prevents brute force attacks
  • Helmet: Sets various HTTP security headers
  • XSS Protection: Prevents cross-site scripting attacks
  • MongoDB Injection: Sanitizes user input
  • CORS: Configures cross-origin resource sharing
  • JWT: Secure token-based authentication
  • Password Hashing: Uses bcrypt for password security

πŸ§ͺ Testing

# Run tests (if implemented)
npm test

# Run tests in watch mode
npm run test:watch

πŸš€ Deployment

Environment Variables for Production

NODE_ENV=production
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/ecom-api
JWT_SECRET=your-super-secure-production-secret
PORT=3000

Deploy to Render

  1. Connect Repository

    • Go to Render Dashboard
    • Click "New +" β†’ "Web Service"
    • Connect your GitHub repository
  2. Configure Settings

    • Name: your-app-name
    • Environment: Node
    • Build Command: npm install
    • Start Command: npm start
  3. Set Environment Variables

    NODE_ENV=production
    MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/ecom-api
    JWT_SECRET=your-super-secure-production-secret
    
  4. Deploy

    • Click "Create Web Service"
    • Render will automatically deploy your app
    • Your API will be available at https://your-app-name.onrender.com

Alternative: Deploy to Heroku

# Login to Heroku
heroku login

# Create Heroku app
heroku create your-app-name

# Set environment variables
heroku config:set MONGO_URI=your-mongo-uri
heroku config:set JWT_SECRET=your-jwt-secret

# Deploy
git push heroku main

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

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


πŸ‘¨β€πŸ’» Author

Your Name


πŸ™ Acknowledgments

  • Express.js - Fast, unopinionated, minimalist web framework
  • MongoDB - NoSQL database
  • Mongoose - MongoDB object modeling for Node.js
  • JWT - JSON Web Tokens for authentication

⭐ Star this repo if you found it helpful!

About

πŸ›’ A complete RESTful API for e-commerce applications built with Node.js, Express, and MongoDB. Features secure JWT authentication, product management, user profiles, review system, and order processing with comprehensive security measures.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published