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
Clone the repository
git clone <repository-url> cd mun-bInstall dependencies
npm installConfigure environment variables
Create a
.envfile 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=Start MongoDB
Make sure MongoDB is running on your system:
# For local MongoDB mongodRun the application
Development mode (with nodemon):
npm run devProduction mode:
node index.jsVerify the server
Open your browser or API client and navigate to:
http://localhost:3001You 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:
- CSV Upload - Saves as
data.csvin./public/temp/ - 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:
- validateAuthRequest - Validates authentication requests
- checkAuth - Verifies JWT tokens
- upload - Handles CSV file uploads
- 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
- Create Model in
src/models/ - Create Repository in
src/repositories/ - Create Service in
src/services/ - Create Controller in
src/controllers/ - 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 devCheck MongoDB connection:
# The console will log:
# "Connected to MongoDB" - Success
# "MongoDB not connected" - Failure📄 License
ISC
👨💻 Author
Mritunjai
- Email: [email protected]
🤝 Contributing
- 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
📌 Notes
- Make sure to change the
JWT_SECRET_KEYin production - Update
DB_URIto point to your MongoDB instance - For Gmail SMTP, use App Passwords
- The email validation currently checks for
@nith.ac.indomain - modify as needed insrc/middlewares/validateAuthRequest.js
🎯 Next Steps
After setting up, you can:
- Create your first model in
src/models/ - Set up authentication routes
- Build your API endpoints
- Add custom middleware as needed
- Implement your business logic
Happy Coding! 🚀
