A production-ready template for building modern Node.js backend applications with TypeScript, Express.js, JWT authentication, and MongoDB. This template provides a solid foundation and boilerplate code for quickly starting new backend projects with authentication, role-based access control, and clean architecture.
- π¦ Ready-to-Use Boilerplate: Complete project structure with all essential components
- π· TypeScript: Full TypeScript support with CommonJS modules and strict type checking
- π JWT Authentication: Complete authentication system with token-based security
- π₯ Role-Based Access Control: Multi-role system (Customer, Admin, Super Admin)
- ποΈ MongoDB Integration: Pre-configured Mongoose models and database connection
- π‘οΈ Security Features: Password hashing with bcryptjs, JWT tokens, and secure configurations
- β‘ Development Ready: Hot-reload development server with ts-node-dev
- ποΈ Clean Architecture: Organized folder structure following MVC best practices
- π§ Environment Configuration: Centralized environment variable management with validation
- π CORS Support: Pre-configured CORS middleware for cross-origin requests
- π Comprehensive Documentation: Well-documented code and API endpoints
Before running this application, make sure you have the following installed:
- Node.js (v18 or higher)
- npm or yarn
- MongoDB (local or MongoDB Atlas)
-
Use this template or clone the repository
# Option 1: Use GitHub template (recommended) # Click "Use this template" button on GitHub # Option 2: Clone the repository git clone <repository-url> cd your-project-name
-
Install dependencies
npm install
-
Environment Setup Create a
.envfile in the root directory and customize these variables:# Server Configuration NODE_ENV=development PORT=3000 HOST=localhost # Database (Replace with your MongoDB connection string) MONGODB_URI=mongodb://localhost:27017/your-database-name # Super Admin Credentials (Customize these - REQUIRED) SUPERADMIN_EMAIL=admin@yourdomain.com SUPERADMIN_PASSWORD=your-secure-admin-password # JWT Configuration (Generate a secure secret - REQUIRED) JWT_SECRET=your-jwt-secret-key-here JWT_EXPIRES_IN=7d # Security BCRYPT_ROUNDS=10 # CORS Configuration CORS_ORIGIN=*
β οΈ Important:MONGODB_URIandJWT_SECRETare required and validated on startup. -
Customize the project
- Update
package.jsonwith your project details - Modify the database name in your MongoDB URI
- Update the super admin credentials
- Customize the User model and routes as needed
- Update
npm run devThis will start the server with hot-reload using Node.js watch mode and ts-node.
# Build the project
npm run build
# Start the production server
npm startThe server will start on http://localhost:3000 (or your configured port).
src/
βββ config/ # Configuration files
β βββ env.ts # Environment variables with validation
βββ controllers/ # Request handlers and business logic
β βββ auth.controller.ts
βββ middlewares/ # Custom middleware functions
β βββ auth.middleware.ts
β βββ role.middleware.ts
βββ models/ # Database models and schemas
β βββ user.model.ts
βββ routes/ # API route definitions
β βββ auth.routes.ts
βββ services/ # Business logic services (expandable)
βββ utils/ # Utility functions
β βββ jwt.util.ts
βββ validators/ # Request validation schemas (expandable)
βββ index.ts # Application entry point
The application implements a role-based authentication system with three user roles:
- CUSTOMER: Basic user role
- ADMIN: Administrative privileges
- SUPERADMIN: Full system access
POST /register- Register a new customerPOST /register-admin- Register a new admin (requires super admin privileges)POST /login- User login
User Registration:
POST /api/v1/auth/register
{
"email": "user@example.com",
"firstName": "John",
"lastName": "Doe",
"password": "securepassword",
"profileimg": "https://example.com/profile.jpg"
}User Login:
POST /api/v1/auth/login
{
"email": "user@example.com",
"password": "securepassword"
}Login Response:
{
"message": "User logged in successfully",
"data": {
"id": "user-id",
"email": "user@example.com",
"accessToken": "jwt-token",
"roles": ["CUSTOMER"]
}
}email: String (unique)firstName: StringlastName: Stringpassword: String (hashed)roles: Array of rolesisBlock: Booleanprofileimg: String
The project uses modern TypeScript configuration with:
- ES2020 target
- CommonJS module system
- Strict type checking enabled
- ESM interoperability
- Source maps for debugging
Production Dependencies:
express(v5.1.0): Fast, unopinionated web frameworkmongoose(v8.19.1): MongoDB object modeling toolbcryptjs(v3.0.2): Password hashing libraryjsonwebtoken(v9.0.2): JWT implementation for authenticationdotenv(v17.2.3): Environment variable loadercors(v2.8.5): Cross-Origin Resource Sharing middleware
Development Dependencies:
typescript(v5.9.3): TypeScript compilerts-node-dev(v2.0.0): Development server with hot reloadts-node(v10.9.2): TypeScript execution environment@types/*: Type definitions for TypeScript
On first run, the application automatically:
- Validates required environment variables (MONGODB_URI, JWT_SECRET)
- Connects to MongoDB
- Creates a Super Admin account using credentials from
.env(if it doesn't exist) - Sets up the database schema
Note: The super admin account will only be created once. If a super admin already exists, the system will skip creation.
- Password Hashing: Using bcryptjs with configurable salt rounds (default: 10)
- JWT Token Authentication: Secure token-based authentication with configurable expiration
- Role-Based Access Control: Middleware for protecting routes by user roles
- Environment Variable Protection: Centralized config with runtime validation
- CORS Configuration: Configurable cross-origin resource sharing
- Input Validation: Ready-to-extend validators directory for request validation
The API follows RESTful conventions and returns JSON responses. All protected routes require a valid JWT token in the Authorization header:
Authorization: Bearer <your-jwt-token>
This template provides:
- β Complete authentication system with JWT (login, register)
- β User registration and admin registration endpoints
- β Role-based middleware for route protection (Customer, Admin, SuperAdmin)
- β MongoDB integration with Mongoose ODM
- β TypeScript configuration with strict type checking
- β Development and production build scripts
- β Centralized environment configuration with validation
- β Security best practices (password hashing, JWT tokens)
- β CORS middleware pre-configured
- β Clean project structure following MVC pattern
- β Auto-creation of super admin on first run
-
Update Project Information
- Change the project name and description in
package.json - Update the database name in your
MONGODB_URIconnection string - Configure
CORS_ORIGINfor your specific domain(s)
- Change the project name and description in
-
Extend the User Model
- Add additional fields to the User schema in
src/models/user.model.ts - Update registration/login controllers in
src/controllers/auth.controller.ts - Modify the JWT payload in
src/utils/jwt.util.tsif needed
- Add additional fields to the User schema in
-
Add New Routes
- Create new route files in
src/routes/ - Add corresponding controllers in
src/controllers/ - Register routes in
src/index.ts(e.g.,app.use("/api/v1/your-route", yourRouter))
- Create new route files in
-
Add Middleware
- Create custom middleware in
src/middlewares/ - Use existing
auth.middleware.tsandrole.middleware.tsas examples - Apply middleware to routes as needed
- Create custom middleware in
-
Add Services
- Create service files in
src/services/for business logic - Keep controllers thin by moving complex logic to services
- Create service files in
-
Add Validators
- Create validation schemas in
src/validators/ - Use libraries like
joiorexpress-validatorfor request validation
- Create validation schemas in
Contributions to improve this template are welcome!
- Fork the project
- Create your feature branch (
git checkout -b feature/TemplateImprovement) - Commit your changes (
git commit -m 'Add some TemplateImprovement') - Push to the branch (
git push origin feature/TemplateImprovement) - Open a Pull Request
This project is licensed under the ISC License.
-
MongoDB Connection Error
- Ensure MongoDB is running locally or your MongoDB Atlas cluster is accessible
- Verify your
MONGODB_URIin the .env file is correct - Check network connectivity and firewall settings
-
Port Already in Use
- Change the
PORTvalue in your .env file - On Windows:
netstat -ano | findstr :<PORT>to find and kill the process
- Change the
-
JWT Token Issues
- Ensure
JWT_SECRETis set in your environment variables - Check token expiration settings (
JWT_EXPIRES_IN) - Verify the Authorization header format:
Bearer <token>
- Ensure
-
Environment Variable Validation Error
- The app validates
MONGODB_URIandJWT_SECRETon startup - Ensure these variables are set in your
.envfile - Check for typos in environment variable names
- The app validates
If you found this template helpful, please consider giving it a star! Feel free to customize it according to your project needs.
Future improvements planned for this template:
- Email verification system
- Password reset functionality
- Refresh token implementation
- API rate limiting middleware
- Request validation with express-validator or joi
- Swagger/OpenAPI documentation
- Docker configuration with docker-compose
- Unit and integration tests with Jest
- Logging system with Winston or Pino
- Database seeding scripts
- File upload handling with multer
- Error handling middleware
π Template for Node.js + Express.js + JWT + TypeScript + MongoDB
Version: 1.0.0
License: ISC
Made with β€οΈ for the developer community