A production-ready, scalable e-commerce REST API built with Node.js, Express, PostgreSQL, and Redis. This API provides comprehensive features for managing products, users, orders, payments, and more with enterprise-grade security and performance optimizations.
- Project Description
- Features
- Prerequisites
- Installation
- Configuration
- Running the Application
- API Documentation
- Testing
- Deployment
- Project Structure
- Technology Stack
- Contributing
- License
This e-commerce REST API is designed to power modern online stores with a robust, scalable backend infrastructure. Built following industry best practices, it implements modular architecture, comprehensive security measures, and optimized performance for handling high-traffic production environments.
Key Highlights:
- Production-ready with Docker containerization
- Secure authentication with JWT and refresh tokens
- Integrated payment processing via Stripe
- Advanced caching with Redis
- Full-text search capabilities
- Role-based access control (RBAC)
- Comprehensive API documentation with Swagger
- Extensive test coverage with Jest
- User registration with email verification
- Secure login/logout with JWT tokens
- Refresh token rotation for enhanced security
- Password hashing with bcrypt (configurable rounds)
- Rate limiting to prevent brute-force attacks
- Role-based access control (Admin, User, Guest)
- Full CRUD operations for products
- Hierarchical category management
- Advanced search with full-text capabilities
- Multi-field filtering and sorting
- Inventory tracking with low stock alerts
- Image upload to AWS S3
- Product variants and SKU management
- Add, update, and remove items
- Real-time price calculations
- Session management with Redis
- Cart persistence for authenticated users
- Product recommendations based on cart contents
- Secure order creation from cart
- Multi-status order tracking (Pending, Processing, Shipped, Delivered, Cancelled)
- Stripe payment integration with webhooks
- Order history with pagination
- Email notifications for order updates
- Invoice generation
- Product management (bulk import/export)
- Order management and fulfillment
- User management and role assignment
- Sales analytics and reporting
- Inventory monitoring
- System health metrics
- Comprehensive logging with Winston
- Error handling middleware
- Input validation and sanitization
- XSS and SQL injection prevention
- CORS configuration
- API rate limiting
- Database connection pooling
- Asynchronous job processing
Before installing, ensure you have the following installed:
- Node.js: v20.x or higher
- npm: v10.x or higher
- PostgreSQL: v14.x or higher
- Redis: v7.x or higher
- Docker & Docker Compose: (Optional, for containerized deployment)
- AWS Account: For S3 storage (or alternative cloud storage)
- Stripe Account: For payment processing
git clone https://github.com/yourusername/node_express_20251104_121321.git
cd node_express_20251104_121321npm install# Create PostgreSQL database
createdb ecommerce_db
# Run migrations
npm run migrate
# Seed initial data (optional)
npm run seed# Start Redis server (if not running)
redis-server
# Or using Docker
docker run -d -p 6379:6379 redis:7-alpineCreate a .env file in the root directory:
# Application
NODE_ENV=development
PORT=3000
API_VERSION=v1
# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=ecommerce_db
DB_USER=postgres
DB_PASSWORD=your_password
DB_POOL_MAX=20
DB_POOL_MIN=5
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0
# JWT
JWT_SECRET=your_jwt_secret_key_here
JWT_REFRESH_SECRET=your_refresh_secret_key_here
JWT_EXPIRES_IN=15m
JWT_REFRESH_EXPIRES_IN=7d
# Bcrypt
BCRYPT_ROUNDS=12
# Email (SMTP)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_email_password
EMAIL_FROM=noreply@yourstore.com
# AWS S3
AWS_ACCESS_KEY_ID=your_aws_access_key
AWS_SECRET_ACCESS_KEY=your_aws_secret_key
AWS_REGION=us-east-1
AWS_S3_BUCKET=your-bucket-name
# Stripe
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_PUBLISHABLE_KEY=pk_test_your_stripe_publishable_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
# CORS
CORS_ORIGIN=http://localhost:3001,https://yourfrontend.com
# Rate Limiting
RATE_LIMIT_WINDOW=15m
RATE_LIMIT_MAX_REQUESTS=100
# Logging
LOG_LEVEL=info
LOG_FILE_PATH=./logsEdit src/config/database.js if needed:
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: 'postgres',
pool: {
max: parseInt(process.env.DB_POOL_MAX),
min: parseInt(process.env.DB_POOL_MIN),
acquire: 30000,
idle: 10000
}
}
};# Start with nodemon (auto-reload)
npm run dev# Build and start
npm start# Build and run all services
docker-compose up -d
# View logs
docker-compose logs -f api
# Stop services
docker-compose downnpm start # Start production server
npm run dev # Start development server with nodemon
npm test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Generate test coverage report
npm run migrate # Run database migrations
npm run migrate:undo # Undo last migration
npm run seed # Seed database with sample data
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint errors
npm run docs # Generate API documentationDevelopment: http://localhost:3000/api/v1
Production: https://api.yourstore.com/api/v1
Most endpoints require a JWT token in the Authorization header:
Authorization: Bearer <your_jwt_token>
POST /api/v1/auth/register
POST /api/v1/auth/login
POST /api/v1/auth/logout
POST /api/v1/auth/refresh-token
POST /api/v1/auth/verify-email
POST /api/v1/auth/forgot-password
POST /api/v1/auth/reset-passwordExample: User Registration
curl -X POST http://localhost:3000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePass123!",
"firstName": "John",
"lastName": "Doe"
}'Response:
{
"success": true,
"message": "Registration successful. Please verify your email.",
"data": {
"userId": "uuid-here",
"email": "user@example.com"
}
}Example: User Login
curl -X POST http://localhost:3000/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePass123!"
}'Response:
{
"success": true,
"data": {
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "uuid-here",
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe",
"role": "user"
}
}
}GET /api/v1/products # List all products (paginated)
GET /api/v1/products/:id # Get single product
POST /api/v1/products # Create product (Admin)
PUT /api/v1/products/:id # Update product (Admin)
DELETE /api/v1/products/:id # Delete product (Admin)
GET /api/v1/products/search # Search products
POST /api/v1/products/:id/images # Upload product image (Admin)Example: Get Products
curl -X GET "http://localhost:3000/api/v1/products?page=1&limit=10&category=electronics&sort=price:asc"Response:
{
"success": true,
"data": {
"products": [
{
"id": "uuid-here",
"name": "Premium Headphones",
"description": "High-quality wireless headphones",
"price": 199.99,
"sku": "HD-001",
"stock": 50,
"category": "electronics",
"images": ["https://s3.amazonaws.com/..."],
"createdAt": "2024-01-15T10:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 150,
"pages": 15
}
}
}Example: Create Product
curl -X POST http://localhost:3000/api/v1/products \
-H "Authorization: Bearer <admin_token>" \
-H "Content-Type: application/json" \
-d '{
"name": "Wireless Mouse",
"description": "Ergonomic wireless mouse",
"price": 29.99,
"sku": "MS-001",
"stock": 100,
"categoryId": "category-uuid"
}'GET /api/v1/categories # List all categories
GET /api/v1/categories/:id # Get single category
POST /api/v1/categories # Create category (Admin)
PUT /api/v1/categories/:id # Update category (Admin)
DELETE /api/v1/categories/:id # Delete category (Admin)GET /api/v1/cart # Get user's cart
POST /api/v1/cart/items # Add item to cart
PUT /api/v1/cart/items/:id # Update cart item quantity
DELETE /api/v1/cart/items/:id # Remove item from cart
DELETE /api/v1/cart # Clear cartExample: Add to Cart
curl -X POST http://localhost:3000/api/v1/cart/items \
-H "Authorization: Bearer <user_token>" \
-H "Content-Type: application/json" \
-d '{
"productId": "product-uuid",
"quantity": 2
}'Response:
{
"success": true,
"data": {
"cart": {
"id": "cart-uuid",
"items": [
{
"id": "item-uuid",
"productId": "product-uuid",
"name": "Wireless Mouse",
"price": 29.99,
"quantity": 2,
"subtotal": 59.98
}
],
"total": 59.98
}
}
}GET /api/v1/orders # Get user's orders
GET /api/v1/orders/:id # Get single order
POST /api/v1/orders # Create order from cart
PUT /api/v1/orders/:id/cancel # Cancel order
GET /api/v1/orders/:id/invoice # Download invoiceExample: Create Order
curl -X POST http://localhost:3000/api/v1/orders \
-H "Authorization: Bearer <user_token>" \
-H "Content-Type: application/json" \
-d '{
"shippingAddress": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"paymentMethodId": "pm_card_visa"
}'Response:
{
"success": true,
"data": {
"order": {
"id": "order-uuid",
"orderNumber": "ORD-20240115-001",
"status": "pending",
"items": [...],
"subtotal": 59.98,
"tax": 4.80,
"shipping": 10.00,
"total": 74.78,
"createdAt": "2024-01-15T10:00:00Z"
},
"paymentIntent": {
"id": "pi_stripe_id",
"clientSecret": "pi_secret_here"
}
}
}GET /api/v1/admin/users # List all users
PUT /api/v1/admin/users/:id/role # Update user role
GET /api/v1/admin/orders # List all orders
PUT /api/v1/admin/orders/:id # Update order status
GET /api/v1/admin/analytics # Get sales analytics
POST /api/v1/admin/products/import # Bulk import products
GET /api/v1/admin/products/export # Bulk export productsAccess interactive API documentation at:
http://localhost:3000/api-docs
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverage
# Run specific test file
npm test -- src/tests/auth.test.js// Example test file: src/tests/auth.test.js
describe('Authentication API', () => {
describe('POST /api/v1/auth/register', () => {
it('should register a new user', async () => {
const response = await request(app)
.post('/api/v1/auth/register')
.send({
email: 'test@example.com',
password: 'SecurePass123!',
firstName: