A production-ready, enterprise-grade Node.js backend template built with TypeScript, featuring modern architecture patterns, comprehensive Docker support, and developer-friendly tooling.
This isn't just another Node.js starter - it's a carefully crafted backend foundation that incorporates industry best practices, clean architecture, and production-ready configurations to give you a significant head start on any backend project.
- Clean Architecture with modular design
- SOLID principles implementation
- Separation of concerns with clear boundaries
- Domain-driven design structure
- JWT-based authentication
- Password hashing with bcrypt
- Input validation with Zod
- CORS protection
- Security headers and best practices
- Multi-stage Dockerfile optimization
- Separate dev/prod environments
- MongoDB integration included
- Health checks and monitoring
- Resource optimization
- Hot-reload development
- Comprehensive logging
- Type safety with TypeScript
- Path aliases for clean imports
- Rich utility scripts
- 🚀 Quick Start
- 🏛️ Architecture
- 🔧 Features
- 🐳 Docker Support
- 📁 Project Structure
- 🔌 API Endpoints
- 🛡️ Security Features
- 📚 Documentation
- 🚀 Deployment
- 🤝 Contributing
- Node.js 20+
- Docker & Docker Compose
- MongoDB (or use Docker)
# Clone the repository
git clone https://github.com/Alikhan018/backend-template.git
cd backend-template
# Start everything with Docker (recommended)
npm run docker:dev
# 🎉 That's it! Your API is running at http://localhost:3000# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Start MongoDB (Docker)
npm run db:start
# Start development server
npm run devThis template follows Clean Architecture principles with a modular, scalable design:
- Layered Architecture: Clear separation between presentation, business, and data layers
- Repository Pattern: Abstract data access logic
- Dependency Injection: Loose coupling between components
- Base Classes: Consistent behavior across modules
- Error-First Design: Comprehensive error handling strategy
Each feature is organized as a self-contained module:
src/modules/[feature]/
├── controllers/ # HTTP request handlers
├── services/ # Business logic
├── models/ # Data models
├── routes/ # Route definitions
├── validators/ # Input validation schemas
├── dtos/ # Data transfer objects
└── interfaces/ # TypeScript interfaces
- ✅ TypeScript - Full type safety and modern JS features
- ✅ Express.js - Fast, minimal web framework
- ✅ MongoDB - Flexible NoSQL database with Mongoose ODM
- ✅ JWT Authentication - Secure token-based auth
- ✅ Winston Logging - Structured logging with file rotation
- ✅ Environment Configuration - Flexible env management
- ✅ Zod Validation - Runtime type checking and validation
- ✅ Password Hashing - bcrypt for secure password storage
- ✅ JWT Middleware - Route-level authentication
- ✅ Input Sanitization - Prevent injection attacks
- ✅ CORS Protection - Configurable cross-origin requests
- ✅ Hot Reload - Instant feedback during development
- ✅ Path Aliases - Clean import statements (
@/modules/...) - ✅ Error Handling - Centralized error management
- ✅ Base Classes - Consistent patterns across modules
- ✅ TypeScript Strict Mode - Maximum type safety
- ✅ Docker Support - Multi-stage builds for dev/prod
- ✅ Docker Compose - Orchestrated services
- ✅ Health Checks - Built-in application monitoring
- ✅ Logging Strategy - Structured logs with rotation
- ✅ Environment Separation - Dev/staging/prod configs
- Development Stage: Hot-reload with full debugging
- Production Stage: Optimized, lightweight containers
- Security: Non-root users and minimal attack surface
# Development with MongoDB
npm run docker:dev
# Production environment
npm run docker:prod
# View logs
npm run docker:logs
# Database management
npm run db:start
npm run db:status
npm run db:logs- Health Checks: Automatic service monitoring
- Resource Limits: Memory and CPU constraints
- Volume Management: Persistent data and hot-reload
- Network Isolation: Secure service communication
- Backup/Restore: Built-in database utilities
backend-template/
├── 📂 src/
│ ├── 📂 configs/ # Configuration modules
│ │ ├── database/ # Database connection
│ │ └── logger/ # Winston logger setup
│ ├── 📂 core/ # Core framework components
│ │ ├── controller/ # Base controller class
│ │ ├── service/ # Base service class
│ │ ├── error/ # Error handling
│ │ └── routes/ # Route registration
│ ├── 📂 modules/ # Feature modules
│ │ ├── auth/ # Authentication module
│ │ └── users/ # User management
│ ├── 📂 middlewares/ # Express middlewares
│ │ ├── auth.middleware.ts
│ │ ├── validate.middleware.ts
│ │ └── role.middleware.ts
│ ├── 📂 environment/ # Environment configuration
│ └── 📂 server/ # Server setup
├── 📂 scripts/ # Utility scripts
│ ├── setup.sh # Environment setup
│ ├── db-setup.sh # Database management
│ └── docker-utils.sh # Docker utilities
├── 📂 logs/ # Application logs
├── 🐳 Dockerfile # Multi-stage Docker build
├── 🐳 docker-compose.yaml # Development environment
├── 🐳 docker-compose.prod.yaml # Production environment
└── 📋 DOCKER.md # Docker documentation
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
POST |
/api/auth/signup |
Register new user | ❌ |
POST |
/api/auth/login |
User login | ❌ |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET |
/api/users |
Get all users | ✅ |
POST |
/api/users |
Create user | ❌ |
GET |
/api/users/:id |
Get user by ID | ✅ |
PUT |
/api/users/:id |
Update user | ✅ |
DELETE |
/api/users/:id |
Delete user | ✅ |
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
GET |
/ |
Health check | ❌ |
🔐 User Registration
curl -X POST http://localhost:3000/api/auth/signup \\
-H "Content-Type: application/json" \\
-d '{
"name": "John Doe",
"email": "[email protected]",
"password": "password123"
}'Response:
{
"success": true,
"message": "Registration successful",
"data": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "[email protected]"
}
}🔑 User Login
curl -X POST http://localhost:3000/api/auth/login \\
-H "Content-Type: application/json" \\
-d '{
"email": "[email protected]",
"password": "password123"
}'Response:
{
"success": true,
"message": "Login successful",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": 3600
}
}- JWT Tokens: Secure, stateless authentication
- Password Hashing: bcrypt with salt rounds
- Token Expiration: Configurable token lifetime
- Route Protection: Middleware-based auth checks
- Zod Schemas: Runtime type checking
- Request Validation: Comprehensive input sanitization
- Error Responses: Detailed validation feedback
- SQL Injection Protection: Parameterized queries
// CORS Configuration
CORS_ORIGIN=http://localhost:3000,https://yourapp.com
// JWT Security
JWT_SECRET=your-super-secure-secret
JWT_EXPIRES_IN=7d
// Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100- 🐳 Docker Setup Guide - Complete Docker documentation
- 🔧 Development Guide - Development best practices
- 🚀 Deployment Guide - Production deployment
- 🔌 API Reference - Complete API documentation
{
"dev": "Start development server with hot-reload",
"build": "Build TypeScript to JavaScript",
"start": "Start production server",
"db:start": "Start MongoDB container",
"db:stop": "Stop MongoDB container",
"db:status": "Check MongoDB status",
"db:logs": "View MongoDB logs",
"docker:dev": "Start development environment",
"docker:prod": "Start production environment",
"docker:down": "Stop all containers",
"docker:logs": "View service logs",
"docker:shell": "Open container shell",
"docker:cleanup": "Clean Docker resources",
"docker:status": "Check container status",
"docker:health": "Health check all services"
}This template is ready for deployment on major cloud platforms:
- AWS ECS/EKS - Container orchestration
- Google Cloud Run - Serverless containers
- Azure Container Instances - Managed containers
- DigitalOcean Apps - Platform-as-a-Service
- Railway - Simple deployment
- Render - Zero-config deployment
# Create production environment
cp .env.production.example .env.production
# Edit with your production values
vim .env.production
# Deploy with Docker Compose
docker-compose -f docker-compose.prod.yaml up -d
# Or use our script
npm run docker:prodCritical environment variables for production:
NODE_ENV=production
PORT=3000
MONGODB_URI=mongodb://username:password@host:port/database
JWT_SECRET=your-super-secure-jwt-secret-change-this
CORS_ORIGIN=https://yourdomain.com- ✅ Battle-tested patterns and practices
- ✅ Scalable architecture that grows with your needs
- ✅ Security-first approach with comprehensive protection
- ✅ Performance optimizations built-in
- ✅ Monitoring and logging ready for production
- ✅ Hot-reload for instant development feedback
- ✅ TypeScript for better code quality and IDE support
- ✅ Clear documentation with examples
- ✅ Utility scripts for common tasks
- ✅ Consistent patterns across the codebase
- ✅ Latest Node.js features and best practices
- ✅ MongoDB with Mongoose for data modeling
- ✅ Docker for consistent environments
- ✅ Winston for professional logging
- ✅ Zod for runtime validation
We welcome contributions! Here's how you can help:
- 📝 Documentation: Improve guides and examples
- 🔧 Features: Add new modules and functionality
- 🐛 Bug Fixes: Report and fix issues
- 🔬 Testing: Add comprehensive test coverage
- 🚀 Performance: Optimize and benchmark
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- ⭐ Stars: Give us a star if you find this useful!
- 🍴 Forks: Fork to create your own version
- 📝 Issues: Report bugs and request features
- 🔄 Pull Requests: Contribute improvements
This project is licensed under the MIT License - see the LICENSE file for details.
Ready to build something amazing?
git clone https://github.com/Alikhan018/backend-template.git
cd backend-template
npm run docker:dev🚀 Your production-ready backend is now running at http://localhost:3000
- Express.js - Fast, unopinionated web framework
- TypeScript - JavaScript that scales
- MongoDB - The application data platform
- Docker - Containerization platform
- Winston - Universal logging library
Built by Muhammad Ali Khan