npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nodejs-mongodb-backend-boilerplate-mritunjai

v1.0.0

Published

Production-ready Node.js + Express + MongoDB backend boilerplate with JWT, file uploads, and email support.

Readme

Node.js MongoDB Backend Boilerplate

A production-ready backend boilerplate built with Node.js, Express, and MongoDB by Mritunjai. This starter template provides a solid foundation for building scalable REST APIs with authentication, file uploads, and email functionality.


🚀 Features

  • Express.js - Fast, unopinionated web framework
  • MongoDB with Mongoose - NoSQL database with elegant ODM
  • JWT Authentication - Secure token-based authentication
  • Email Integration - Built-in Nodemailer configuration
  • File Upload - Multer middleware for handling multipart/form-data
  • CORS Enabled - Cross-Origin Resource Sharing configured
  • Environment Variables - Secure configuration management with dotenv
  • Modular Architecture - Clean separation of concerns (MVC pattern)
  • Error Handling - Centralized error response utilities
  • API Versioning - Structured routing with version support (v1)

📁 Project Structure

mun-b/
├── src/
│   ├── config/           # Configuration files
│   │   ├── db-config.js
│   │   ├── mail-config.js
│   │   ├── server-config.js
│   │   └── index.js
│   ├── controllers/      # Request handlers
│   ├── middlewares/      # Custom middleware
│   │   ├── validateAuthRequest.js
│   │   ├── multer.js
│   │   └── index.js
│   ├── models/           # Mongoose schemas
│   ├── repositories/     # Data access layer
│   ├── routes/           # API routes
│   │   ├── v1/
│   │   └── index.js
│   ├── services/         # Business logic
│   └── utils/            # Utility functions
│       ├── common/       # Common utilities
│       │   ├── error-response.js
│       │   └── success-response.js
│       └── errors/       # Custom error classes
├── public/
│   └── temp/             # Temporary file storage
├── .env                  # Environment variables
├── .gitignore
├── index.js              # Application entry point
├── package.json
└── README.md

🛠️ Installation

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (local or cloud instance)
  • npm or yarn

Steps

  1. Clone the repository

    git clone <repository-url>
    cd mun-b
  2. Install dependencies

    npm install
  3. Configure environment variables

    Create a .env file in the root directory:

    DB_URI=mongodb://localhost:27017/YourDatabaseName
    BACKEND_PORT=3001
    JWT_SECRET_KEY=your_secret_key_here
    JWT_EXPIRE=1d
    EXPIRES_IN=1d
    [email protected]
    ADMIN_EMAIL_PASSWORD=your_app_password
    ADMIN_EMAIL2=
    ADMIN_EMAIL_PASSWORD2=
  4. Start MongoDB

    Make sure MongoDB is running on your system:

    # For local MongoDB
    mongod
  5. Run the application

    Development mode (with nodemon):

    npm run dev

    Production mode:

    node index.js
  6. Verify the server

    Open your browser or API client and navigate to:

    http://localhost:3001

    You should see: Server is running.........


🔧 Configuration

Database Configuration

Located in src/config/db-config.js

  • Configures MongoDB connection URI
  • Sets Mongoose options

Server Configuration

Located in src/config/server-config.js

  • Port configuration
  • JWT settings
  • Admin email credentials

Mail Configuration

Located in src/config/mail-config.js

  • Nodemailer transport setup
  • Email service configuration

🔐 Authentication

This boilerplate includes JWT-based authentication middleware:

Features:

  • Token Generation - JWT tokens with configurable expiration
  • Token Verification - Middleware to protect routes
  • Email Validation - Custom validation for NIT Hamirpur emails (@nith.ac.in)
  • Authorization Headers - Bearer token authentication

Usage Example:

// Protect a route
const { checkAuth } = require('./src/middlewares/validateAuthRequest');

router.get('/protected-route', checkAuth, controller.handler);

📤 File Upload

Multer middleware is configured for handling file uploads:

Two Upload Types:

  1. CSV Upload - Saves as data.csv in ./public/temp/
  2. Image Upload - Saves with timestamp in ./public/temp/image/

Usage Example:

const { upload, uploadImage } = require('./src/middlewares/multer');

// CSV upload
router.post('/upload-csv', upload.single('file'), controller.handler);

// Image upload
router.post('/upload-image', uploadImage.single('image'), controller.handler);

📧 Email Service

Nodemailer is integrated for sending emails:

  • Configured in src/config/mail-config.js
  • Supports multiple admin email accounts
  • Ready for transactional emails, notifications, etc.

🛣️ API Routes

Routes are organized with versioning support:

/api/v1/...

Add your routes in src/routes/v1/index.js


🧩 Middleware

Available Middleware:

  1. validateAuthRequest - Validates authentication requests
  2. checkAuth - Verifies JWT tokens
  3. upload - Handles CSV file uploads
  4. uploadImage - Handles image uploads

📦 Dependencies

| Package | Purpose | |---------|---------| | express | Web framework | | mongoose | MongoDB ODM | | cors | Enable CORS | | dotenv | Environment variables | | nodemailer | Email sending | | multer | File upload handling | | jsonwebtoken | JWT authentication | | http-status-codes | HTTP status constants |


🚦 API Response Format

Success Response

{
  "success": true,
  "message": "Operation successful",
  "data": { ... }
}

Error Response

{
  "success": false,
  "message": "Error message",
  "error": {
    "statusCode": 400,
    "explanation": ["Detailed error explanation"]
  }
}

📝 Development Guidelines

Adding a New Feature

  1. Create Model in src/models/
  2. Create Repository in src/repositories/
  3. Create Service in src/services/
  4. Create Controller in src/controllers/
  5. Add Routes in src/routes/v1/

Best Practices

  • Keep business logic in services
  • Use repositories for database operations
  • Validate requests in controllers
  • Use middleware for cross-cutting concerns
  • Follow the existing folder structure

🔒 Security Features

  • JWT Authentication - Secure token-based auth
  • Environment Variables - Sensitive data protection
  • CORS Configuration - Controlled cross-origin access
  • Password Validation - Request validation middleware
  • Error Handling - Prevents information leakage

🐛 Debugging

Run with nodemon for auto-restart on file changes:

npm run dev

Check MongoDB connection:

# The console will log:
# "Connected to MongoDB" - Success
# "MongoDB not connected" - Failure

📄 License

ISC


👨‍💻 Author

Mritunjai


🤝 Contributing

  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

📌 Notes

  • Make sure to change the JWT_SECRET_KEY in production
  • Update DB_URI to point to your MongoDB instance
  • For Gmail SMTP, use App Passwords
  • The email validation currently checks for @nith.ac.in domain - modify as needed in src/middlewares/validateAuthRequest.js

🎯 Next Steps

After setting up, you can:

  1. Create your first model in src/models/
  2. Set up authentication routes
  3. Build your API endpoints
  4. Add custom middleware as needed
  5. Implement your business logic

Node.js MongoDB License


Happy Coding! 🚀