Skip to content

A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose

Notifications You must be signed in to change notification settings

rohitsoni007/node-express-mongodb

Repository files navigation

Node.js Express MongoDB Boilerplate πŸš€

A production-ready, scalable boilerplate for building RESTful APIs with Node.js, Express, and MongoDB. Built with security, performance, and developer experience in mind.

Node.js Express MongoDB License

🌟 Features

  • πŸ” 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

πŸ“š API Documentation

This boilerplate comes with built-in API documentation powered by Swagger/OpenAPI specifications. The following packages are integrated to provide comprehensive API documentation:

Swagger Autogen

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 swagger to regenerate the documentation
  • Configuration: Located in utils/swagger.js

Swagger UI Express

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

Elements Express

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

πŸš€ Quick Start

Prerequisites

  • Node.js 18.x or higher
  • MongoDB database (local or cloud)
  • npm, yarn, or pnpm package manager

Installation

# 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 install

Docker Installation (Alternative)

Instead 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-boilerplate

Note: MongoDB is not included in the Docker setup. You need to have MongoDB running externally and configure the MONGO_URI in your .env file to point to your MongoDB instance.

Environment Variables

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

Running the Application

# 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

Running with Docker

# Using Docker Compose (recommended)
docker-compose up

# Using Docker only
docker build -t node-express-boilerplate .
docker run -p 3000:3000 node-express-boilerplate

Note: Make sure you have MongoDB running externally and have configured the MONGO_URI in your .env file before starting the Docker container.

πŸš€ Production Deployment with PM2

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 prod

This 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 myapp

PM2 ensures your application stays running even if it crashes and can automatically restart it on system reboot.

πŸ—οΈ Project Structure

.
β”œβ”€β”€ 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

πŸ”§ Core Components

Authentication System

  • 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

Caching Layer

  • 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

Security Features

  • 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

πŸ“‘ API Endpoints

Authentication Routes

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

πŸ§ͺ Testing

Run the test suite with:

npm test
# or in watch mode
npm run test:watch

Tests are written with Jest and Supertest for API testing. MongoDB Memory Server is used for database mocking during tests.

πŸ“¦ Dependencies

Core Dependencies

  • 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

Development Dependencies

  • nodemon: Auto-restart server during development
  • prettier: Opinionated code formatter
  • jest: Delightful JavaScript testing framework
  • swagger-autogen: Automatically generate Swagger documentation from code

πŸ› οΈ Development Scripts

{
  "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"
}

πŸ“ˆ Performance Optimizations

  • 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

πŸ”’ Best Practices Implemented

  • 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

πŸ“ File Uploads

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
});

AWS S3 File Uploads

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_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_S3_BUCKET_NAME
  • AWS_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
});

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

✨ Acknowledgments

  • 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!

About

A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published