Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎯 MERN eCommerce - Production Ready

Status: βœ… Full Stack Complete | πŸ“¦ Ready for Deployment | πŸ“š Production-Grade Code

Node.js React Express MongoDB JWT License


πŸ“š What's Inside

A production-grade MERN eCommerce application built with industry best practices:

  • βœ… 32 API Endpoints - Complete CRUD operations
  • βœ… 4 Core Modules - Auth, Products, Cart, Orders
  • βœ… Modern React Frontend - Redux, React Router, Responsive UI
  • βœ… Enterprise Security - JWT, bcrypt, rate limiting, CORS
  • βœ… Advanced Admin Panel - Analytics, inventory, user management
  • βœ… Production Ready - Error handling, logging, validation
  • βœ… Scalable Architecture - MVC pattern, service layer, middleware stack

πŸš€ Quick Start

Prerequisites

Node.js v14+
MongoDB (local or Atlas)
npm or yarn

Backend Setup

cd backend
npm install
cp .env.example .env
# Update MONGO_URI in .env
npm run seed  # Seed sample data
npm run dev   # Development server

Frontend Setup

cd frontend
npm install
npm start     # Development server on http://localhost:3000
npm run build # Production build

Production Deployment

# Backend
cd backend
npm run build  # If using build script
npm start

# Frontend (serve build folder)
cd frontend
npm run build
npx serve -s build -l 3000

πŸ”§ API Endpoints

Authentication

  • POST /api/v1/auth/register - User registration
  • POST /api/v1/auth/login - User login
  • GET /api/v1/auth/me - Get current user
  • POST /api/v1/auth/logout - Logout

Products

  • GET /api/v1/products - Get all products (with filters)
  • GET /api/v1/products/featured - Get featured products
  • GET /api/v1/products/:id - Get product by ID
  • GET /api/v1/products/categories - Get categories

Cart

  • GET /api/v1/cart - Get user cart
  • POST /api/v1/cart/add - Add item to cart
  • PUT /api/v1/cart/update/:itemId - Update cart item
  • DELETE /api/v1/cart/remove/:itemId - Remove from cart

Orders

  • POST /api/v1/orders/create - Create order
  • GET /api/v1/orders/my-orders - Get user orders
  • GET /api/v1/orders/:orderId - Get order details

πŸ›  Tech Stack

Backend:

  • Node.js + Express.js
  • MongoDB + Mongoose
  • JWT Authentication
  • bcrypt Password Hashing
  • Express Rate Limiting
  • CORS + Helmet Security
  • Morgan Logging
  • Joi Validation

Frontend:

  • React 18 + React Router
  • Redux Toolkit + Redux Persist
  • Axios for API calls
  • React Toastify
  • React Icons
  • CSS Modules

πŸ“ Project Structure

eCommerce-Website/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ controllers/     # Business logic
β”‚   β”œβ”€β”€ models/         # MongoDB schemas
β”‚   β”œβ”€β”€ routes/         # API routes
β”‚   β”œβ”€β”€ middleware/     # Custom middleware
β”‚   β”œβ”€β”€ services/       # Business services
β”‚   β”œβ”€β”€ utils/          # Helper functions
β”‚   └── scripts/        # Database seeding
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/ # Reusable components
β”‚   β”‚   β”œβ”€β”€ pages/      # Page components
β”‚   β”‚   β”œβ”€β”€ store/      # Redux store
β”‚   β”‚   └── services/   # API services
β”‚   └── public/         # Static assets
└── README.md

πŸ”’ Security Features

  • JWT token authentication
  • Password hashing with bcrypt
  • Rate limiting on all routes
  • CORS protection
  • Helmet security headers
  • Input validation and sanitization
  • SQL injection prevention
  • XSS protection

πŸ“Š Features

User Features

  • User registration and login
  • Product browsing with filters
  • Shopping cart functionality
  • Order placement and tracking
  • User profile management
  • Wishlist functionality

Admin Features

  • User management
  • Product CRUD operations
  • Order management
  • Analytics dashboard
  • Inventory management

πŸš€ Deployment

The application is production-ready and can be deployed to:

  • Backend: Heroku, DigitalOcean, AWS, Vercel
  • Frontend: Netlify, Vercel, AWS S3
  • Database: MongoDB Atlas

Environment Variables

Create .env file in backend root:

MONGO_URI=mongodb://localhost:27017/ecommerce
PORT=5001
NODE_ENV=production
JWT_SECRET=your_super_secret_key
JWT_EXPIRE=7d
REFRESH_TOKEN_SECRET=your_refresh_secret
REFRESH_TOKEN_EXPIRE=30d
CORS_ORIGIN=https://yourdomain.com

πŸ“ License

MIT License - feel free to use this project for learning and commercial purposes.


🀝 Contributing

  1. Fork the repository
  2. Create feature branch
  3. Commit changes
  4. Push to branch
  5. Create Pull Request

Happy Coding! πŸŽ‰


Server runs at: **http://localhost:5000**

### Test an Endpoint
```bash
curl http://localhost:5000/api/v1/products

πŸ“Š Project Structure

backend/
β”œβ”€β”€ controllers/          # Request handlers (32 functions)
β”œβ”€β”€ services/            # Business logic layer
β”œβ”€β”€ routes/v1/           # API endpoints (v1 versioning)
β”œβ”€β”€ models/              # MongoDB schemas (4 models)
β”œβ”€β”€ middleware/          # Auth, errors, rate limiting
β”œβ”€β”€ config/              # Database connection
β”œβ”€β”€ utils/               # Logger, JWT, password, validation
β”œβ”€β”€ server.js            # Express app entry
β”œβ”€β”€ package.json         # Dependencies
└── .env                 # Environment variables

πŸ”‘ 32 API Endpoints

Authentication (10)

POST   /api/v1/auth/register
POST   /api/v1/auth/login
GET    /api/v1/auth/me
POST   /api/v1/auth/logout
POST   /api/v1/auth/refresh-token
PUT    /api/v1/auth/update-profile
POST   /api/v1/auth/change-password
GET    /api/v1/auth/users/all              (Admin)
PUT    /api/v1/auth/users/:userId/role     (Admin)
DELETE /api/v1/auth/users/:userId          (Admin)

Products (8)

GET    /api/v1/products                   (Search, Filter, Sort, Paginate)
GET    /api/v1/products/:id
GET    /api/v1/products/categories
GET    /api/v1/products/brands
GET    /api/v1/products/category/:category
POST   /api/v1/products                   (Admin)
PUT    /api/v1/products/:id               (Admin)
DELETE /api/v1/products/:id               (Admin)

Cart (6)

GET    /api/v1/cart
GET    /api/v1/cart/summary
POST   /api/v1/cart/add
PUT    /api/v1/cart/:itemId
DELETE /api/v1/cart/:itemId
DELETE /api/v1/cart                       (Clear)

Orders (8)

POST   /api/v1/orders
POST   /api/v1/orders/verify-payment
GET    /api/v1/orders
GET    /api/v1/orders/:orderId
GET    /api/v1/orders/track/:orderId
DELETE /api/v1/orders/:orderId/cancel
GET    /api/v1/orders/admin/all           (Admin)
PUT    /api/v1/orders/admin/:orderId/status (Admin)

πŸ” Security Features

βœ… JWT Authentication - Stateless, token-based βœ… Password Security - bcryptjs hashing (10 rounds) βœ… Rate Limiting - 5 auth/15min, 100 global/15min βœ… Account Lockout - 5 failed attempts β†’ 30min lock βœ… Role-Based Access - Admin/User permissions βœ… Input Validation - Sanitized with express-validator βœ… CORS Protection - Configurable origins βœ… Helmet Security - Sets secure HTTP headers βœ… Stock Validation - Prevents overselling βœ… User Isolation - Can't access others' data


πŸ“Š Database Models

User

{
  name, email, password (hashed),
  role: 'user' | 'admin',
  phone, address, city, state, zipCode,
  loginAttempts, accountLocked, lockUntil,
  refreshTokens: [],
  createdAt, updatedAt
}

Product

{
  name, description, price, discount,
  brand, category,
  sizes: [], colors: [],
  images: [{url, public_id}],
  ratings, numReviews, stock,
  createdBy: ObjectId (admin),
  createdAt, updatedAt
}

Cart

{
  user: ObjectId (unique),
  items: [{
    product: ObjectId,
    quantity, size, color,
    price (with discount),
    addedAt
  }],
  totalPrice (auto-calculated),
  createdAt, updatedAt
}

Order

{
  user: ObjectId,
  items: [{product, quantity, price}],
  totalPrice,
  shippingAddress: {street, city, state, zipCode, country, phone},
  paymentInfo: {method, transactionId, status},
  orderStatus: 'pending'|'confirmed'|'shipped'|'delivered'|'cancelled',
  trackingNumber, estimatedDelivery,
  createdAt, updatedAt
}

πŸ“š Documentation

File Purpose
BACKEND_READY.md Quick start guide
MASTER_SUMMARY.md Complete overview
INDUSTRIAL_LEARNING_GUIDE.md 5-year dev perspective
AUTH_API_DOCS.md Auth endpoints
PRODUCT_API_DOCS.md Product endpoints
CART_API_DOCS.md Cart endpoints
ORDER_API_DOCS.md Order endpoints
DOCUMENTATION_INDEX.md Navigation guide

πŸ› οΈ Tech Stack

Backend Framework

  • Node.js - Runtime
  • Express.js - Web framework
  • Mongoose - MongoDB ODM

Authentication

  • JWT - Token-based auth
  • bcryptjs - Password hashing
  • jsonwebtoken - Token generation

Security

  • Helmet - Security headers
  • CORS - Cross-origin handling
  • express-rate-limit - Rate limiting
  • express-validator - Input validation

Development

  • Nodemon - Auto-reload
  • Morgan - HTTP logging
  • Dotenv - Environment variables

Database

  • MongoDB - NoSQL database
  • MongoDB Atlas - Cloud option

πŸš€ Deployment

Option 1: Render (Recommended)

1. Push to GitHub
2. Connect Render to GitHub
3. Configure environment variables
4. Deploy automatically

Option 2: Railway

1. Install Railway CLI
2. Connect to GitHub
3. Deploy with: railway up

Option 3: Heroku

1. Install Heroku CLI
2. heroku login
3. git push heroku main

Option 4: AWS / DigitalOcean

1. Create droplet/instance
2. Install Node.js, MongoDB
3. Clone repo & npm install
4. Set up systemd service
5. Configure domain & SSL

πŸ“ Environment Variables

# Database
MONGO_URI=mongodb://localhost:27017/ecommerce
# Or MongoDB Atlas: mongodb+srv://user:pass@cluster.mongodb.net/ecommerce

# Server
PORT=5000
NODE_ENV=development

# JWT
JWT_SECRET=your_super_secret_jwt_key_min_32_chars
JWT_EXPIRE=7d
REFRESH_TOKEN_SECRET=your_super_secret_refresh_key_min_32_chars
REFRESH_TOKEN_EXPIRE=30d

# Security
CORS_ORIGIN=http://localhost:3000,http://localhost:5173

# Payment (Mock)
RAZORPAY_KEY_ID=test_key
RAZORPAY_KEY_SECRET=test_secret

# Redis (Optional)
REDIS_URL=redis://localhost:6379

# Cloudinary (Optional)
CLOUDINARY_CLOUD_NAME=your_cloudinary_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

πŸ§ͺ Testing

Health Check

curl http://localhost:5000/health

Register User

curl -X POST http://localhost:5000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "SecurePass123",
    "confirmPassword": "SecurePass123"
  }'

Get Products

curl "http://localhost:5000/api/v1/products?category=electronics&sortBy=price-low&limit=20"

With Postman

  1. Import API examples from documentation files
  2. Set BASE_URL environment variable
  3. Use provided curl commands

πŸŽ“ Learning Path

For Beginners

  1. Read BACKEND_READY.md
  2. Follow quick start
  3. Test endpoints with curl
  4. Read API documentation

For Intermediate

  1. Study INDUSTRIAL_LEARNING_GUIDE.md
  2. Review code in /backend
  3. Understand design patterns
  4. Extend with new endpoints

For Advanced

  1. Study architecture from MASTER_SUMMARY.md
  2. Implement Redis caching
  3. Add unit & integration tests
  4. Deploy to production

πŸ“ˆ Features & Status

BACKEND
βœ… Authentication System          100% Complete
βœ… Product Management             100% Complete
βœ… Shopping Cart                  100% Complete
βœ… Order Processing               100% Complete
βœ… Payment Integration (Mock)     100% Complete
βœ… Admin Analytics                100% Complete
βœ… User Management                100% Complete
βœ… Inventory Management           100% Complete
βœ… Error Handling                 100% Complete
βœ… Security (all layers)          100% Complete

FRONTEND (Coming)
⏳ React Setup
⏳ Redux State Management
⏳ Product Listing UI
⏳ Shopping Experience
⏳ Admin Dashboard

DEPLOYMENT (Coming)
⏳ Docker Setup
⏳ CI/CD Pipeline
⏳ Production Checklist
⏳ Scaling Guide

πŸ”„ API Response Format

All endpoints follow consistent format:

// Success (200, 201, etc.)
{
  "status": true,
  "message": "Operation successful",
  "data": {
    /* endpoint-specific data */
  }
}

// Error (400, 404, 500, etc.)
{
  "status": false,
  "message": "Error description",
  "data": null
}

πŸ›‘οΈ Security Headers

Server automatically sets:

Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin

πŸ“Š Performance Metrics

  • ⚑ Query Optimization - Lean queries, pagination, indexing
  • πŸ”„ Caching Ready - Redis integration prepared
  • πŸ“Š Database - Indexed searches, optimized joins
  • πŸš€ Scalability - Service layer architecture
  • πŸ“ˆ Monitoring - Logging system in place

🀝 Contributing

  1. Fork repository
  2. Create feature branch
  3. Commit changes
  4. Push and create PR

πŸ“„ License

MIT License - See LICENSE file


🎯 Roadmap

Phase 1: Backend βœ…

  • Authentication System
  • Product Module
  • Cart System
  • Order Processing
  • Admin Panel
  • Analytics Dashboard

Phase 2: Frontend (MASTER PROMPT 7-8)

  • React App Setup
  • Redux Store
  • Product Listing UI
  • Shopping Cart UI
  • Checkout Flow
  • Admin Dashboard

Phase 3: Advanced (MASTER PROMPT 9-10)

  • Redis Caching
  • Image Optimization
  • Performance Tuning
  • Load Testing
  • Production Deployment
  • CI/CD Pipeline

πŸ“ž Support

For questions or issues:

  1. Check documentation files
  2. Review API examples
  3. Check error logs
  4. Create GitHub issue

πŸŽ‰ Getting Started

# 1. Clone repo
git clone <your-repo>

# 2. Install dependencies
cd backend && npm install

# 3. Configure environment
cp .env.example .env
# Edit .env with your MongoDB URI

# 4. Start server
npm start

# 5. Read documentation
open BACKEND_READY.md

# 6. Test endpoints
curl http://localhost:5000/health

πŸ“š Featured In

This project is built following practices used by:

  • Flipkart - India's largest e-commerce
  • Amazon - Global e-commerce leader
  • Myntra - Fashion e-commerce
  • Uber - Real-time ordering
  • Airbnb - Complex filtering

πŸ† Best Practices Implemented

βœ… MVC Architecture βœ… Service Layer Pattern βœ… Async/Await Error Handling βœ… Input Validation & Sanitization βœ… JWT Authentication βœ… Role-Based Authorization βœ… Rate Limiting βœ… Database Indexing βœ… Pagination & Lean Queries βœ… Error Logging βœ… CORS & Security Headers βœ… Environment Configuration


πŸŽ“ Learn MERN Stack

After setting up, explore:

  • INDUSTRIAL_LEARNING_GUIDE.md - Architecture & design patterns
  • API Documentation - How each endpoint works
  • Code Structure - Why organized this way
  • Security - How it protects against attacks
  • Performance - Optimization techniques

Ready to build the future of e-commerce? Let's code! πŸš€


Made with ❀️ for MERN developers

About

`A full-stack MERN eCommerce website with authentication, product management, cart, wishlist, orders, payments, and admin panel.`

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages