Skip to content

A professional CLI tool to scaffold a production-ready MERN backend with a clean architecture, best practices, and minimal setup.

License

Notifications You must be signed in to change notification settings

adityashriwas/create-mern-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

create-mern-api

npm version License: MIT Node.js Version

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


🎯 About

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

✨ Features

  • 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

πŸ“‹ Requirements

Requirement Version
Node.js >= 18
npm >= 9
MongoDB Local or Cloud (Atlas)

πŸš€ Installation

Global Installation (Recommended)

npm install -g create-mern-api

One-Time Usage

npx create-mern-api my-backend

⚑ Quick Start

1. Create Your Backend

npx create-mern-api my-backend
cd my-backend

2. Configure Environment Variables

Update 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=10d

3. Start Development Server

npm run dev

Server will start at http://localhost:8000


πŸ“ Project Structure

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

Architecture Highlights

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


πŸ“¦ Included Dependencies

Production Dependencies

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

Development Dependencies

  • nodemon - Auto-restart on file changes
  • eslint - Code linting
  • prettier - Code formatting
  • eslint-config-prettier - ESLint + Prettier integration

πŸ› οΈ Available Scripts

# 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:check

πŸ“‹ Configuration Guide

Environment Variables

Server Configuration

  • PORT - Server port (default: 8000)

Database Configuration

  • MONGODB_URI - MongoDB connection string
    • Local: mongodb://localhost:27017/database-name
    • Atlas: mongodb+srv://user:pass@cluster.mongodb.net/database-name

Security Configuration

  • CORS_ORIGIN - Frontend origin(s) for CORS
  • ACCESS_TOKEN_SECRET - Secret key for JWT access tokens
  • REFRESH_TOKEN_SECRET - Secret key for JWT refresh tokens

Token Expiry

  • ACCESS_TOKEN_EXPIRY - Access token validity (e.g., 7d, 24h)
  • REFRESH_TOKEN_EXPIRY - Refresh token validity (e.g., 10d)

Customizing ESLint & Prettier

eslint.config.js - Configure linting rules prettier.config.js - Adjust code formatting style .prettierignore - Exclude files from formatting


πŸ” Authentication

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

πŸ“š API Response Format

Success Response

{
  "statusCode": 200,
  "data": {
    "id": "...",
    "name": "..."
  },
  "message": "Data retrieved successfully",
  "success": true
}

Error Response

{
  "statusCode": 400,
  "message": "Validation error",
  "errors": ["field error details"],
  "success": false
}

🌟 Best Practices Included

  • βœ… 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

πŸš€ Getting Help

Common Issues

MongoDB Connection Error

  • Ensure MongoDB is running
  • Check MONGODB_URI in .env
  • Verify network access in MongoDB Atlas

Port Already in Use

  • Change PORT in .env
  • Or kill process: lsof -i :8000 (Mac/Linux) or netstat -ano (Windows)

Module Not Found

  • Run npm install again
  • Delete node_modules and reinstall: rm -rf node_modules && npm install

Learning Resources


πŸ“„ License

MIT Β© 2025 Aditya Shriwas

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


🀝 Contributing

Found a bug or have suggestions? Contributions are welcome!

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

πŸ’‘ Philosophy

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

Why use create-mern-api?

Most MERN developers waste time re-writing:

  • Express setup
  • Database connection logic
  • Auth boilerplate
  • Error handling
  • Folder structures

This CLI removes that friction.


Customization

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

Author

Aditya Shriwas


License

MIT License

About

A professional CLI tool to scaffold a production-ready MERN backend with a clean architecture, best practices, and minimal setup.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published