# Express + TypeScript + MongoDB API Boilerplate
# ===============================================
# Quick Start
# ------------
# 1. Clone or create the project structure below.
# 2. Run `npm install`
# 3. Copy `.env.example` to `.env` and update values (e.g., MONGO_URI).
# 4. Run `npm run dev` for development.
# 5. Run `npm run build` then `npm start` for production.
# Project Structure
# -----------------
project-root/
├── src/
│ ├── config/
│ │ └── database.ts
│ ├── controllers/
│ │ └── userController.ts
│ ├── middleware/
│ │ └── errorHandler.ts
│ ├── models/
│ │ └── User.ts
│ ├── routes/
│ │ └── userRoutes.ts
│ ├── types/
│ │ └── express.d.ts
│ ├── app.ts
│ └── server.ts
├── .env.example
├── .gitignore
├── package.json
├── tsconfig.json
└── README.md # (This file)
1. package.json
{
"name": "express-ts-mongo-boilerplate",
"version": "1.0.0",
"description": "Boilerplate for Express + TypeScript + MongoDB API",
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"start": "node dist/server.js",
"dev": "nodemon",
"lint": "eslint src/**/*.ts",
"test": "jest"
},
"keywords": ["express", "typescript", "mongodb", "mongoose", "api"],
"author": "",
"license": "MIT",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"helmet": "^7.1.0",
"mongoose": "^8.5.1"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^22.5.0",
"@typescript-eslint/eslint-plugin": "^7.15.0",
"@typescript-eslint/parser": "^7.15.0",
"eslint": "^8.57.0",
"nodemon": "^3.1.4",
"ts-node": "^10.9.2",
"typescript": "^5.5.3"
}
}
2. tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
3. .env.example (Copy to .env and fill in values)
PORT=3000
MONGO_URI=mongodb://localhost:27017/myappdb
NODE_ENV=development
4. .gitignore
node_modules/
dist/
.env
*.log
coverage/
.DS_Store
5. src/types/express.d.ts (Custom Express types)
import { Request } from 'express';
declare global {
namespace Express {
interface Request {
user?: any; // Extend for auth later
}
}
}
6. src/config/database.ts
import mongoose from 'mongoose';
import dotenv from 'dotenv';
dotenv.config();
const connectDB = async (): Promise<void> => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI as string);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error('Database connection error:', error);
process.exit(1);
}
};
export default connectDB;
7. src/models/User.ts
import { Schema, model, Document } from 'mongoose';
export interface IUser extends Document {
name: string;
email: string;
age: number;
}
const userSchema = new Schema<IUser>({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, required: true },
}, { timestamps: true });
export default model<IUser>('User', userSchema);
8. src/controllers/userController.ts
import { Request, Response } from 'express';
import User, { IUser } from '../models/User';
export const getUsers = async (req: Request, res: Response): Promise<void> => {
try {
const users: IUser[] = await User.find();
res.status(200).json({ success: true, data: users });
} catch (error) {
res.status(500).json({ success: false, message: 'Server error' });
}
};
export const createUser = async (req: Request, res: Response): Promise<void> => {
try {
const user: IUser = new User(req.body);
await user.save();
res.status(201).json({ success: true, data: user });
} catch (error: any) {
if (error.code === 11000) {
res.status(400).json({ success: false, message: 'Email already exists' });
} else {
res.status(500).json({ success: false, message: 'Server error' });
}
}
};
9. src/routes/userRoutes.ts
import { Router } from 'express';
import { getUsers, createUser } from '../controllers/userController';
const router = Router();
router.get('/', getUsers);
router.post('/', createUser);
export default router;
10. src/middleware/errorHandler.ts
import { Request, Response, NextFunction } from 'express';
export const errorHandler = (
err: any,
req: Request,
res: Response,
next: NextFunction
): void => {
console.error(err.stack);
res.status(500).json({ success: false, message: 'Something went wrong!' });
};
11. src/app.ts
import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import userRoutes from './routes/userRoutes';
import { errorHandler } from './middleware/errorHandler';
const app: Application = express();
// Security & Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Routes
app.use('/api/users', userRoutes);
// Health check
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK', timestamp: new Date().toISOString() });
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({ success: false, message: 'Route not found' });
});
// Global error handler
app.use(errorHandler);
export default app;
12. src/server.ts
import app from './app';
import connectDB from './config/database';
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 3000;
const startServer = async (): Promise<void> => {
try {
await connectDB();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
};
startServer();
Usage Examples
- GET all users:
http://localhost:3000/api/users
- POST user:
http://localhost:3000/api/users with JSON body { "name": "John", "email": "john@example.com", "age": 30 }
- Health check:
http://localhost:3000/health
Next Steps
- Add authentication (JWT/Passport).
- Add validation (Zod/Joi).
- Add logging (Winston).
- Add tests (Jest/Supertest).
- Deploy (Docker, PM2, Vercel, etc.).
This boilerplate is production-ready for basics: secure headers, CORS, error handling, TypeScript strict mode, and MongoDB connection. Extend as needed! 🚀