A comprehensive RESTful API for an e-commerce platform built with Node.js, TypeScript, Express.js, Prisma ORM, and MongoDB.
- JWT-based authentication and authorization
- Role-based access control (Admin/Customer)
- Complete product management
- Shopping cart functionality
- Order processing with stock management
- Request logging and validation
- Structured error handling
- Dockerized setup for easy deployment
- Runtime: Node.js
- Language: TypeScript
- Framework: Express.js
- Database: MongoDB
- ORM: Prisma
- Authentication: JWT (JSON Web Tokens)
- Validation: Zod
- Logging: Morgan
- Containerization: Docker & Docker Compose
ecommerce-api/
├── src/
│ ├── controllers/ # Request handlers
│ ├── routes/ # API routes
│ ├── services/ # Business logic
│ ├── middleware/ # Custom middleware
│ ├── validators/ # Zod validation schemas
│ ├── utils/ # Utility functions
│ ├── types/ # TypeScript types
│ └── index.ts # Application entry point
├── prisma/
│ ├── schema.prisma # Database schema
│ └── seed.ts # Database seeding script
├── Dockerfile # Docker configuration
├── docker-compose.yml # Docker Compose configuration
├── tsconfig.json # TypeScript configuration
├── package.json # Dependencies
└── .env # Environment variables
- Docker and Docker Compose installed on your system
- OR Node.js 18+ and MongoDB installed locally
git clone <repository-url>
cd ecommerce-apiThe .env file is already created with default values. You can modify it if needed:
DATABASE_URL="mongodb://mongodb:27017/ecommerce?authSource=admin"
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"
PORT=3000
NODE_ENV="development"docker-compose up --buildThis command will:
- Start MongoDB container
- Build and start the API container
- Run Prisma migrations
- Make the API available at
http://localhost:3000
In a new terminal, run:
docker-compose exec api npm run seedThis will populate the database with sample data including:
- 3 users (1 admin, 2 customers)
- 10 products across different categories
- Sample cart items and orders
Test Credentials:
- Admin:
admin@example.com/password123 - Customer 1:
john@example.com/password123 - Customer 2:
jane@example.com/password123
npm installUpdate the .env file with your local MongoDB connection:
DATABASE_URL="mongodb://localhost:27017/ecommerce"
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"
PORT=3000
NODE_ENV="development"npm run prisma:generatenpm run prisma:pushnpm run seednpm run devThe API will be available at http://localhost:3000
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/auth/register |
Register new user | No |
| POST | /api/auth/login |
Login user | No |
| GET | /api/auth/profile |
Get user profile | Yes |
| PUT | /api/auth/profile |
Update user profile | Yes |
| Method | Endpoint | Description | Auth Required | Role |
|---|---|---|---|---|
| GET | /api/products |
Get all products | No | - |
| GET | /api/products/:id |
Get product by ID | No | - |
| GET | /api/products/category/:category |
Get products by category | No | - |
| POST | /api/products |
Create product | Yes | Admin |
| PUT | /api/products/:id |
Update product | Yes | Admin |
| DELETE | /api/products/:id |
Delete product | Yes | Admin |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /api/cart |
Add item to cart | Yes |
| GET | /api/cart |
Get user's cart | Yes |
| DELETE | /api/cart/:id |
Remove item from cart | Yes |
| DELETE | /api/cart |
Clear cart | Yes |
| Method | Endpoint | Description | Auth Required | Role |
|---|---|---|---|---|
| POST | /api/orders |
Create order from cart items | Yes | Customer |
| GET | /api/orders |
Get user's orders | Yes | Customer |
| GET | /api/orders/all |
Get all orders | Yes | Admin |
| GET | /api/orders/:id |
Get order by ID | Yes | Customer/Admin |
| PATCH | /api/orders/:id/status |
Update order status | Yes | Admin |
POST /api/auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"role": "CUSTOMER"
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}POST /api/products
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "Laptop",
"description": "High-performance laptop",
"price": 1299.99,
"stock": 50,
"category": "Electronics"
}POST /api/cart
Authorization: Bearer <token>
Content-Type: application/json
{
"productId": "product_id_here",
"quantity": 2
}POST /api/orders
Authorization: Bearer <token>
Content-Type: application/json
{
"items": [
{
"productId": "product_id_here",
"quantity": 1
}
]
}Import the postman_collection.json file into Postman to get a complete collection of API requests.
- Open Postman
- Click Import
- Select
postman_collection.json - The collection includes variables and automatic token management
- id (ObjectId)
- name (String)
- email (String, unique)
- password (String, hashed)
- role (ADMIN | CUSTOMER)
- createdAt (DateTime)
- updatedAt (DateTime)
- id (ObjectId)
- name (String)
- description (String)
- price (Float)
- stock (Integer)
- category (String)
- createdAt (DateTime)
- updatedAt (DateTime)
- id (ObjectId)
- userId (ObjectId, reference to User)
- productId (ObjectId, reference to Product)
- quantity (Integer)
- id (ObjectId)
- userId (ObjectId, reference to User)
- totalAmount (Float)
- status (PENDING | PAID | SHIPPED | COMPLETED | CANCELLED)
- createdAt (DateTime)
- updatedAt (DateTime)
- id (ObjectId)
- orderId (ObjectId, reference to Order)
- productId (ObjectId, reference to Product)
- quantity (Integer)
- price (Float) - Price at the time of order
When an order is created:
- The system validates that sufficient stock exists for all items
- Product stock is automatically decremented by the ordered quantity
- The user's cart is automatically cleared after successful order creation
The API uses structured error responses:
{
"success": false,
"message": "Error description",
"errors": [] // Optional validation errors
}HTTP Status Codes:
- 200: Success
- 201: Created
- 400: Bad Request (validation errors)
- 401: Unauthorized (invalid/missing token)
- 403: Forbidden (insufficient permissions)
- 404: Not Found
- 500: Internal Server Error
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm run prisma:generate- Generate Prisma Clientnpm run prisma:push- Push schema changes to databasenpm run prisma:studio- Open Prisma Studio (database GUI)npm run seed- Seed database with sample data
# Build and start containers
docker-compose up --build
# Start containers in detached mode
docker-compose up -d
# Stop containers
docker-compose down
# View logs
docker-compose logs -f api
# Access API container shell
docker-compose exec api sh
# Seed database in Docker
docker-compose exec api npm run seed
# View Prisma Studio (run locally, not in Docker)
npm run prisma:studio- Passwords are hashed using bcryptjs with salt rounds
- JWT tokens are used for authentication
- Role-based access control for admin operations
- Input validation using Zod schemas
- Environment variables for sensitive data
- CORS enabled for cross-origin requests
Before deploying to production:
- Change
JWT_SECRETto a strong, random value - Update
NODE_ENVtoproduction - Configure proper MongoDB connection with authentication
- Set up proper logging and monitoring
- Configure CORS to allow only specific origins
- Use environment-specific
.envfiles - Set up SSL/TLS for HTTPS
- Implement rate limiting
- Add proper backup strategies for MongoDB
ISC
For issues or questions, please open an issue in the repository.