๐ A production-ready Express.js boilerplate with TypeScript, featuring robust authentication, logging, monitoring, and best practices for building secure and scalable APIs.
If this boilerplate helps your project take off, consider giving it a โญ๏ธ - it fuels my cosmic journey! ๐
- TypeScript - Strongly typed language for better developer experience
- Authentication & Authorization - JWT-based auth with refresh tokens
- Database Integration - Prisma ORM with MySQL
- API Documentation - REST client files for API testing
- Security
- Helmet for security headers
- Rate limiting
- CORS configuration
- Request validation using Zod
- Monitoring & Logging
- Prometheus metrics
- Grafana dashboards
- Winston logger with daily rotate
- Request ID tracking
- Performance
- Response compression
- Caching middleware
- Database connection pooling
- Testing
- Jest for unit and integration tests
- E2E testing setup
- Test helpers and utilities
- Docker Support
- Multi-stage builds
- Docker Compose for local development
- Health checks
- CI/CD
- GitHub Actions workflow
- Automated testing
- Docker image publishing
- Node.js (v18 or higher)
- MySQL (v8.0 or higher)
- Docker and Docker Compose (optional)
- Clone the repository:
git clone https://github.com/mzubair481/express-boilerplate.git
cd express-boilerplate- Install dependencies:
npm install- Set up environment variables:
cp .env.example .env- Set up the database:
npm run migrate:dev
npm run seed:dev- Start the development server:
npm run devRun the entire stack using Docker Compose:
# Start all services
npm run docker:dev
# View logs
npm run docker:dev:logs
# Rebuild and start services
npm run docker:dev:build
# Stop services and remove volumes
npm run docker:dev:downThe development environment is configured with:
- Nodemon for automatic server restart
- Volume mounts for real-time code changes
- TypeScript compilation on save
- Environment variables for development
# Key configurations in docker-compose.dev.yml
services:
api:
volumes:
- ./src:/app/src:delegated # Source code
- ./prisma:/app/prisma:delegated # Prisma schema
- api_node_modules:/app/node_modules
environment:
- NODE_ENV=development
- CHOKIDAR_USEPOLLING=true
- CHOKIDAR_INTERVAL=1000This will start:
- Express API server (http://localhost:4300)
- MySQL database (port 3306)
- Prometheus metrics (http://localhost:9090)
- Grafana dashboards (http://localhost:3000)
- Node Exporter (system metrics)
- Alertmanager (alerts management)
-
Grafana:
- URL: http://localhost:3000
- Default credentials:
- Username:
admin - Password:
admin
- Username:
- Pre-configured dashboards:
- API Metrics Dashboard
- System Metrics Dashboard
-
Prometheus:
- URL: http://localhost:9090
- Metrics endpoint: http://localhost:4300/monitoring/metrics
-
Alertmanager:
- Real-time metrics visualization
- Request rate and latency tracking
- Error rate monitoring
- Garbage Collection metrics
- Node.js process statistics
- CPU and memory usage
- Custom alerts configuration
- System metrics via Node Exporter
- Automated alert notifications
npm run dev- Start development servernpm run build- Build for productionnpm start- Start production server with GC metrics enablednpm test- Run testsnpm run test:e2e- Run E2E testsnpm run test:coverage- Generate test coveragenpm run migrate:dev- Run database migrationsnpm run seed:dev- Seed database with test datanpm run studio- Open Prisma Studio
# Build and start services
docker-compose up -d --build
# Stop services
docker-compose down
# View logs
docker-compose logs -f [service]
# Restart a service
docker-compose restart [service]
# Remove volumes (database data)
docker-compose down -vโโโ src/
โ โโโ __tests__/ # Test files
โ โโโ @types/ # TypeScript type definitions
โ โโโ config/ # Configuration files
โ โโโ controllers/ # Route controllers
โ โโโ middleware/ # Express middleware
โ โโโ routes/ # API routes
โ โโโ services/ # Business logic
โ โโโ utils/ # Utility functions
โ โโโ validators/ # Request validation schemas
โ โโโ app.ts # Express app setup
โ โโโ index.ts # Application entry point
โโโ prisma/ # Prisma schema and migrations
โโโ requests/ # REST client files
โโโ docker/ # Docker configuration files
The API is fully documented using OpenAPI/Swagger. You can access the interactive documentation at:
http://localhost:4300/api-docs
POST /api/auth/signup- Register new userPOST /api/auth/login- User loginPOST /api/auth/refresh- Refresh access tokenPOST /api/auth/logout- User logoutGET /api/auth/verify-email/:token- Verify emailPOST /api/auth/send-email-verification- Resend verification emailPOST /api/auth/forgot-password- Request password resetPOST /api/auth/reset-password/:token- Reset password
GET /api/users- Get all users (Admin only)GET /api/users/:id- Get user by IDPOST /api/users- Create user (Admin only)PATCH /api/users/:id- Update userDELETE /api/users/:id- Delete user (Admin only)
GET /health- Service health checkGET /api/monitoring/metrics- Prometheus metricsGET /api/monitoring/readiness- Readiness probeGET /api/monitoring/liveness- Liveness probe
All protected endpoints require a valid JWT token in the Authorization header:
Authorization: Bearer <your_jwt_token>
POST /api/auth/signup
{
"email": "user@example.com",
"password": "SecurePass123!",
"name": "John Doe"
}
Response 201:
{
"success": true,
"message": "User registered successfully",
"data": {
"id": "uuid",
"email": "user@example.com",
"name": "John Doe"
}
}POST /api/auth/login
{
"email": "user@example.com",
"password": "SecurePass123!"
}
Response 200:
{
"success": true,
"message": "Login successful",
"data": {
"accessToken": "jwt_token",
"refreshToken": "refresh_token"
}
}The API uses standardized error responses:
{
"success": false,
"message": "Error message",
"code": "ERR_XXXX",
"stack": "Error stack trace (development only)"
}- Auth endpoints: 5 requests per minute
- API endpoints: 100 requests per minute
- WebSocket connections: 60 messages per minute
The API provides Prometheus metrics at /api/monitoring/metrics including:
- HTTP request duration
- Request counts by endpoint
- Error rates
- Active WebSocket connections
- System metrics
- User signs up โ Verification email sent
- User verifies email via link
- User can now login
- Login returns access & refresh tokens
- Use access token in Authorization header:
Bearer <token>
- User requests password reset โ Reset email sent
- User clicks reset link in email
- User sets new password using reset token
- User can login with new password
-
Connection
- URL:
ws://localhost:4300 - Secure URL:
wss://your-domain.com(production)
- URL:
-
Message Format:
{
"type": "message_type",
"data": {
// message payload
}
}- Supported Message Types:
ping- Health check ping// Client -> Server { "type": "ping" } // Server -> Client { "type": "pong", "data": { "timestamp": 1234567890 } }
connection- Initial connection confirmation// Server -> Client { "type": "connection", "data": { "clientId": "abc123", "message": "Connected to WebSocket server" } }
// Connect to WebSocket server
const ws = new WebSocket('ws://localhost:4300');
// Handle connection open
ws.onopen = () => {
console.log('Connected to WebSocket server');
};
// Handle incoming messages
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
// Handle different message types
switch (message.type) {
case 'connection':
console.log('Connected with ID:', message.data.clientId);
break;
case 'pong':
console.log('Ping response received');
break;
}
};
// Handle errors
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Handle connection close
ws.onclose = () => {
console.log('Disconnected from WebSocket server');
};
// Send a ping message
ws.send(JSON.stringify({ type: 'ping' }));- Authentication is required for certain message types
- Rate limiting is applied to prevent abuse
- Messages are validated for proper format and content
- Connections are automatically closed after prolonged inactivity
- SSL/TLS encryption is required in production
The application uses structured error codes for better error handling:
- 1xxx: Authentication Errors (e.g., ERR_1001)
- 2xxx: Authorization Errors
- 3xxx: Validation Errors
- 4xxx: Resource Errors
- 5xxx: Database Errors
- 6xxx: Server Errors
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests.
This project is licensed under the MIT License - see the LICENSE file for details.
