A professional CLI tool to scaffold a production-ready MERN backend with clean architecture, industry best practices, and zero configuration overhead.
Build scalable, maintainable backend applications in seconds. Ship faster, code better. π
Features β’ Installation β’ Quick Start β’ Project Structure β’ Configuration β’ Scripts
create-mern-api eliminates repetitive boilerplate and architectural decisions, letting developers focus on building features instead of setting up infrastructure. This CLI scaffolds a fully-configured Express.js backend following industry best practices, complete with MongoDB integration, authentication-ready middleware, centralized error handling, and code quality tools.
Perfect for:
- Building production-grade REST APIs
- Starting enterprise projects quickly
- Learning MERN architecture patterns
- Creating API microservices
- Teaching backend development
- Express.js 5.x - Modern, minimal web framework with ES modules
- MongoDB & Mongoose - Document database with schema validation
- Authentication Ready - JWT-based auth structure with bcrypt password hashing
- Centralized Error Handling - Custom API error classes and response formatting
- Scalable Architecture - Clean folder structure following industry standards
- CORS & Security - Pre-configured cross-origin and security middleware
- Environment Variables - 12-factor app methodology with dotenv
- Code Quality - ESLint + Prettier for consistent, professional code
- Hot Reload - Nodemon for rapid development
- Dependency Management - Pre-selected, production-tested packages
| Requirement | Version |
|---|---|
| Node.js | >= 18 |
| npm | >= 9 |
| MongoDB | Local or Cloud (Atlas) |
npm install -g create-mern-apinpx create-mern-api my-backendnpx create-mern-api my-backend
cd my-backendUpdate the .env file with your configuration:
# Server Configuration
PORT=8000
# Database Configuration
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database-name
# CORS Configuration
CORS_ORIGIN=http://localhost:3000
# JWT Configuration
ACCESS_TOKEN_SECRET=your-super-secret-access-token-key
ACCESS_TOKEN_EXPIRY=7d
REFRESH_TOKEN_SECRET=your-super-secret-refresh-token-key
REFRESH_TOKEN_EXPIRY=10dnpm run devServer will start at http://localhost:8000
The generated backend follows a clean, layered architecture:
my-backend/
βββ src/
β βββ controllers/ # Request handlers & business logic
β β βββ user.controller.js # Example user controller
β βββ routes/ # API route definitions
β β βββ user.route.js # Example user routes
β βββ models/ # MongoDB schemas
β β βββ user.model.js # Example user model
β βββ middlewares/ # Express middleware
β β βββ auth.middleware.js # JWT authentication
β βββ database/ # Database configuration
β β βββ db.js # MongoDB connection
β βββ utils/ # Utility functions
β β βββ ApiError.js # Error handling class
β β βββ ApiResponse.js # Standard response formatting
β β βββ asyncHandler.js # Async error wrapper
β βββ constants.js # Application constants
β βββ app.js # Express app configuration
β βββ index.js # Server entry point
βββ .env # Environment variables (gitignored)
βββ .env.example # Environment template
βββ .prettierrc # Code formatting config
βββ .prettierignore # Prettier ignore rules
βββ .gitignore # Git ignore rules
βββ eslint.config.js # ESLint configuration
βββ package.json # Dependencies & scripts
βββ package-lock.json # Dependency lock file
βββ README.md # Project documentation
Layered Architecture: Clean separation of concerns
- Controllers - Handle HTTP requests, validate input, call services
- Models - Define data schemas and validations
- Routes - Define API endpoints and route handlers
- Middlewares - Handle cross-cutting concerns (auth, logging, etc.)
- Utils - Reusable utility functions and helpers
Error Handling: Custom ApiError class for consistent error responses
Response Formatting: Standardized ApiResponse class for all API responses
Async Handling: asyncHandler wrapper to eliminate try-catch boilerplate
| Package | Purpose | Version |
|---|---|---|
| express | Web framework | ^5.2.1 |
| mongoose | MongoDB ODM | ^9.1.2 |
| jsonwebtoken | JWT authentication | ^9.0.3 |
| bcryptjs | Password hashing | ^3.0.3 |
| cors | Cross-origin requests | ^2.8.5 |
| cookie-parser | Cookie parsing | ^1.4.7 |
| dotenv | Environment variables | ^17.2.3 |
- nodemon - Auto-restart on file changes
- eslint - Code linting
- prettier - Code formatting
- eslint-config-prettier - ESLint + Prettier integration
# Start development server with hot reload
npm run dev
# Start production server
npm start
# Lint code
npm run lint
# Auto-fix linting issues
npm run lint:fix
# Format code with Prettier
npm run format
# Check formatting without changes
npm run format:checkPORT- Server port (default: 8000)
MONGODB_URI- MongoDB connection string- Local:
mongodb://localhost:27017/database-name - Atlas:
mongodb+srv://user:pass@cluster.mongodb.net/database-name
- Local:
CORS_ORIGIN- Frontend origin(s) for CORSACCESS_TOKEN_SECRET- Secret key for JWT access tokensREFRESH_TOKEN_SECRET- Secret key for JWT refresh tokens
ACCESS_TOKEN_EXPIRY- Access token validity (e.g.,7d,24h)REFRESH_TOKEN_EXPIRY- Refresh token validity (e.g.,10d)
eslint.config.js - Configure linting rules prettier.config.js - Adjust code formatting style .prettierignore - Exclude files from formatting
The template includes JWT-based authentication with:
- Secure password hashing using bcryptjs
- JWT token generation and validation
- Refresh token mechanism for long-lived sessions
- Authentication middleware for protected routes
Example authentication flow:
// Controllers can use the auth middleware
import { verifyJWT } from '../middlewares/auth.middleware.js';
app.get('/api/v1/users/profile', verifyJWT, (req, res) => {
// User is authenticated
res.json(req.user);
});{
"statusCode": 200,
"data": {
"id": "...",
"name": "..."
},
"message": "Data retrieved successfully",
"success": true
}{
"statusCode": 400,
"message": "Validation error",
"errors": ["field error details"],
"success": false
}- β Clean Code - Consistent formatting with ESLint & Prettier
- β Error Handling - Centralized error management
- β Security - CORS, helmet-ready, environment variables
- β Database - Mongoose schema validation
- β Async/Await - Modern async patterns with error handling
- β Modular - Easy to extend with new routes/models
- β Documentation - Self-documenting code structure
- β Development - Hot reload with Nodemon
MongoDB Connection Error
- Ensure MongoDB is running
- Check
MONGODB_URIin.env - Verify network access in MongoDB Atlas
Port Already in Use
- Change
PORTin.env - Or kill process:
lsof -i :8000(Mac/Linux) ornetstat -ano(Windows)
Module Not Found
- Run
npm installagain - Delete
node_modulesand reinstall:rm -rf node_modules && npm install
MIT Β© 2025 Aditya Shriwas
This project is licensed under the MIT License - see the LICENSE file for details.
Found a bug or have suggestions? Contributions are welcome!
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
We believe backend development should be:
- Fast - No wasted time on boilerplate
- Professional - Following industry standards and best practices
- Flexible - Easy to extend and customize
- Learner-Friendly - Clear, well-organized code structure
This tool embodies these principles by providing a production-ready foundation that developers can build upon with confidence.
Made with β€οΈ by Aditya Shriwas
β Star on GitHub β’ π¦ NPM Package β’ π Report Issue
This CLI follows these principles:
- No unnecessary abstractions
- Clear separation of concerns
- Easy onboarding for new developers
- Production-oriented defaults
Most MERN developers waste time re-writing:
- Express setup
- Database connection logic
- Auth boilerplate
- Error handling
- Folder structures
This CLI removes that friction.
The generated backend is intentionally minimal.
You are expected to:
- Add business logic
- Extend routes and controllers
- Customize authentication and authorization
- Plug in additional services as needed
Aditya Shriwas
MIT License