A production-ready, scalable boilerplate for building RESTful APIs with Node.js, Express, and MongoDB. Built with security, performance, and developer experience in mind.
- π Authentication & Authorization - JWT-based authentication with role-based access control
- π‘οΈ Security - Helmet, CORS, rate limiting, and XSS protection
- π Caching - In-memory and Redis caching for improved performance
- π¦ Data Validation - Joi validation for request payloads
- ποΈ Database - MongoDB with Mongoose ODM
- π§ Error Handling - Comprehensive error handling middleware
- π Logging - Morgan logging for HTTP requests
- π¨ Template Engine - Handlebars for server-side rendering
- β‘ Performance - Compression middleware for faster responses
- π§ͺ Testing - Vitest for unit and integration testing
- π Documentation - Standardized response format and API documentation ready with Swagger/OpenAPI
- π Development Tools - Nodemon for hot reloading, Prettier for code formatting
- π File Uploads - Multer middleware for handling file uploads with validation
This boilerplate comes with built-in API documentation powered by Swagger/OpenAPI specifications. The following packages are integrated to provide comprehensive API documentation:
Automatically generates OpenAPI (Swagger) documentation from your code comments and Express routes. The documentation is generated in JSON format and saved to swagger.json.
- Package:
swagger-autogen - Usage: Run
npm run swaggerto regenerate the documentation - Configuration: Located in
utils/swagger.js
Provides a beautiful, interactive web interface for viewing your API documentation.
- Package:
swagger-ui-express - Access at:
http://localhost:3000/api-docs - Features:
- Interactive API testing
- Detailed endpoint descriptions
- Request/response examples
- Authentication support
An alternative modern UI for your OpenAPI documentation with a clean, responsive design.
- Package:
elements-express - Access at:
http://localhost:3000/docs - Features:
- Modern, responsive design
- Try-it-out functionality
- Syntax highlighting
- Markdown support
- Node.js 18.x or higher
- MongoDB database (local or cloud)
- npm, yarn, or pnpm package manager
# Clone the repository
git clone https://github.com/rohitsoni007/node-express-mongodb.git
# Navigate to the project directory
cd node-express-mongodb-boilerplate
# Install dependencies
npm install
# or
yarn install
# or
pnpm installInstead of installing dependencies locally, you can use Docker:
# Build and run with Docker Compose
docker-compose up --build
# Or build and run with Docker only
docker build -t node-express-boilerplate .
docker run -p 3000:3000 node-express-boilerplateNote: MongoDB is not included in the Docker setup. You need to have MongoDB running externally and configure the
MONGO_URIin your.envfile to point to your MongoDB instance.
Create a .env file in the root directory and add the following variables:
NODE_ENV=development
PORT=3000
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret_key
REDIS_URL=your_redis_connection_string_optional# Development mode with hot reload
npm run dev
# Production mode
npm start
# Production mode with PM2 (recommended for production)
npm run prod
# Run tests
npm test# Using Docker Compose (recommended)
docker-compose up
# Using Docker only
docker build -t node-express-boilerplate .
docker run -p 3000:3000 node-express-boilerplateNote: Make sure you have MongoDB running externally and have configured the
MONGO_URIin your.envfile before starting the Docker container.
For production environments, it's recommended to use PM2 (Process Manager 2) to manage your Node.js application. PM2 provides features like automatic restarts, load balancing, and monitoring.
To start the application with PM2:
npm run prodThis command will start your application using PM2 with the name "myapp". You can manage your application using PM2 commands:
# View application status
pm2 status
# View application logs
pm2 logs myapp
# Restart the application
pm2 restart myapp
# Stop the application
pm2 stop myapp
# Delete the application from PM2
pm2 delete myappPM2 ensures your application stays running even if it crashes and can automatically restart it on system reboot.
.
βββ bin/ # Server entry point
βββ config/ # Database and other configurations
βββ controllers/ # Request handlers
βββ middleware/ # Custom middleware functions
βββ models/ # Database models
βββ public/ # Static assets
βββ routes/ # API routes
βββ tests/ # Test files
βββ utils/ # Utility functions
βββ validation/ # Request validation schemas
βββ views/ # Handlebars templates
βββ app.js # Express application setup
βββ package.json # Project dependencies and scripts
- Login/Register: Secure user authentication with hashed passwords
- JWT Tokens: Stateless authentication with refresh token support
- Role-Based Access: Different permission levels for users
- Password Management: Forgot/reset password functionality
- Memory Cache: Built-in in-memory caching for frequently accessed data
- Redis Support: Optional Redis integration for distributed caching
- Cache Middleware: Easy-to-use middleware for caching API responses
- Cache Invalidation: Automatic and manual cache invalidation strategies
- Helmet: Secures Express apps with various HTTP headers
- Rate Limiting: Prevents abuse by limiting request frequency
- CORS: Configurable Cross-Origin Resource Sharing
- Input Validation: Joi validation to sanitize and validate inputs
- XSS Protection: Automatic sanitization of user inputs
| Method | Endpoint | Description |
|---|---|---|
| POST | /auth/register |
Register a new user |
| POST | /auth/login |
Login existing user |
| GET | /auth/me |
Get current user info |
| POST | /auth/forgot-password |
Request password reset |
| POST | /auth/reset-password |
Reset password |
| POST | /auth/change-password |
Change user password |
Run the test suite with:
npm test
# or in watch mode
npm run test:watchTests are written with Jest and Supertest for API testing. MongoDB Memory Server is used for database mocking during tests.
- express: Fast, unopinionated web framework
- mongoose: MongoDB object modeling tool
- jsonwebtoken: JSON Web Token implementation
- bcrypt: Library for password hashing
- joi: Schema description language and data validator
- helmet: Security middleware
- cors: Cross-Origin Resource Sharing middleware
- express-rate-limit: Rate limiting middleware
- cache-manager: Flexible caching layer
- @keyv/redis: Redis adapter for caching
- multer: Middleware for handling multipart/form-data (file uploads)
- multer-s3: Middleware for uploading files directly to AWS S3
- swagger-ui-express: Swagger UI for API documentation
- elements-express: Modern UI for OpenAPI documentation
- nodemon: Auto-restart server during development
- prettier: Opinionated code formatter
- jest: Delightful JavaScript testing framework
- swagger-autogen: Automatically generate Swagger documentation from code
{
"start": "node ./bin/www",
"dev": "nodemon ./bin/www",
"prod": "pm2 start ./bin/www --name myapp",
"test": "jest",
"test:watch": "jest --watch",
"format": "prettier --write .",
"format:check": "prettier --check .",
"swagger": "node utils/swagger.js"
}- Response Compression: Reduces payload size by up to 70%
- Database Query Optimization: Efficient Mongoose queries with indexing
- Caching Strategy: Multi-layer caching with automatic invalidation
- Connection Pooling: Efficient database connection management
- Environment-based Configuration: Separate configs for dev/staging/prod
- Error Logging: Centralized error handling and logging
- API Versioning Ready: Structure prepared for API versioning
- Consistent Response Format: Unified API response structure
- Code Organization: Modular structure following MVC pattern
- Security Headers: Proper HTTP headers for enhanced security
This boilerplate includes a fully configured Multer middleware for handling file uploads with validation, size limits, and error handling. Check out the Middleware Documentation for detailed usage instructions.
Example usage:
const {
uploadSingle,
uploadMultiple,
handleMulterErrors,
} = require('../middleware/multer.middleware');
router.post('/upload', uploadSingle, handleMulterErrors, (req, res) => {
// Handle uploaded file
});The boilerplate also includes support for uploading files directly to AWS S3 using the multerS3 middleware. This requires AWS credentials to be configured in your environment variables:
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_S3_BUCKET_NAMEAWS_REGION(optional, defaults to 'us-east-1')
Example usage:
const {
uploadS3Single,
uploadS3Multiple,
handleMulterS3Errors,
} = require('../middleware/multerS3.middleware');
router.post('/upload/s3', uploadS3Single, handleMulterS3Errors, (req, res) => {
// Handle uploaded file to S3
// File location available as req.file.location
});Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Thanks to the Express.js team for the excellent framework
- Inspired by various Node.js boilerplates and best practices
- Built with β€οΈ for the developer community
Ready to build your next Node.js API? This boilerplate gives you a solid foundation with all essential features pre-configured!