Comprehending the Blueprint
I'm starting to build a basic understanding of what the project needs. Right now, I'm focusing on the user's ultimate aim. It's becoming clear that an Express API, built with TypeScript and connected to MongoDB, is the core deliverable. Next up, identifying the project requirements and best practices.
Deconstructing the Requirements
I'm now fully immersed in the nitty-gritty. I'm breaking down the client's needs into actionable steps. My goal is to use Express, TypeScript and MongoDB, with particular focus on modularity. Next, I need to figure out where to start by putting it all together in the best way.
Structuring the Foundation
I'm now mapping out the boilerplate's skeletal framework. I'm focusing on the necessary dependencies and their configurations, particularly TypeScript settings and environment variables. The User example implementation, the directory layout, and the database connection logic are next on my list. The structure has to be well-defined.
Planning the Boilerplate's Contents
I'm now detailing each component of the boilerplate. The project's structure, focusing on essential dependencies and configuration files, is in its final form. Next up, I need to finalize the code snippets, including the User model and controller, and carefully explain the reasons behind those design decisions. I will also incorporate self-correction and edge-case handling, based on common project issues.
Outlining the Final Structure
I'm now consolidating the plan. I'm focusing on the user's practical application with clear instructions and example code. I'm finalizing the directory structure, crucial files and dependencies, and also integrating troubleshooting, which I believe is useful. Finally, I will ensure proper comments and clear explanations.
Here is a complete, production-ready boilerplate for a REST API using Node.js, Express, TypeScript, and MongoDB (Mongoose).
This setup includes:
- Modular Structure: Separation of routes, controllers, and models.
- Type Safety: Full TypeScript integration.
- Hot Reloading: configured with
nodemon and ts-node.
- Security/Utils: Includes
helmet, cors, and dotenv.
1. Project Initialization & Dependencies
Run these commands in your terminal to create the folder and install packages.
mkdir express-ts-mongo-api
cd express-ts-mongo-api
npm init -y
# Install Production Dependencies
npm install express mongoose dotenv cors helmet morgan
# Install Development Dependencies
npm install -D typescript ts-node nodemon @types/node @types/express @types/mongoose @types/cors @types/morgan @types/helmet rimraf
2. TypeScript Configuration (tsconfig.json)
Create a tsconfig.json file in the root directory.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
3. Project Structure
Create the following folder structure:
express-ts-mongo-api/
├── src/
│ ├── config/
│ │ └── db.ts
│ ├── controllers/
│ │ └── userController.ts
│ ├── models/
│ │ └── User.ts
│ ├── routes/
│ │ └── userRoutes.ts
│ ├── app.ts
│ └── index.ts
├── .env
├── .gitignore
├── package.json
└── tsconfig.json
4. Code Implementation
A. Environment Variables (.env)
Create a .env file in the root.
PORT=3000
MONGO_URI=mongodb://localhost:27017/express-ts-boilerplate
B. Database Connection (src/config/db.ts)
import mongoose from 'mongoose';
const connectDB = async (): Promise<void> => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI || '');
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.error(`Error: ${(error as Error).message}`);
process.exit(1);
}
};
export default connectDB;
C. The Model (src/models/User.ts)
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
name: string;
email: string;
role: string;
createdAt: Date;
}
const UserSchema: Schema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
role: { type: String, default: 'user' },
}, {
timestamps: true
});
export default mongoose.model<IUser>('User', UserSchema);
D. The Controller (src/controllers/userController.ts)
import { Request, Response } from 'express';
import User, { IUser } from '../models/User';
// @desc Create a new user
// @route POST /api/users
export const createUser = async (req: Request, res: Response): Promise<void> => {
try {
const { name, email, role } = req.body;
const userExists = await User.findOne({ email });
if (userExists) {
res.status(400).json({ message: 'User already exists' });
return;
}
const user: IUser = await User.create({ name, email, role });
res.status(201).json(user);
} catch (error) {
res.status(500).json({ message: (error as Error).message });
}
};
// @desc Get all users
// @route GET /api/users
export const getUsers = async (req: Request, res: Response): Promise<void> => {
try {
const users = await User.find();
res.status(200).json(users);
} catch (error) {
res.status(500).json({ message: (error as Error).message });
}
};
E. The Routes (src/routes/userRoutes.ts)
import { Router } from 'express';
import { createUser, getUsers } from '../controllers/userController';
const router = Router();
router.post('/', createUser);
router.get('/', getUsers);
export default router;
F. Express App Setup (src/app.ts)
This separates the app configuration from the server startup, which is useful for testing.
import express, { Application } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import userRoutes from './routes/userRoutes';
const app: Application = express();
// Middleware
app.use(express.json());
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));
// Routes
app.use('/api/users', userRoutes);
// Health Check
app.get('/', (req, res) => {
res.send('API is running...');
});
export default app;
G. Server Entry (src/index.ts)
import dotenv from 'dotenv';
import app from './app';
import connectDB from './config/db';
dotenv.config();
const PORT = process.env.PORT || 3000;
// Connect to Database then start server
connectDB().then(() => {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
});
5. Update package.json scripts
Modify the scripts section in package.json to handle building and watching.
"scripts": {
"start": "node dist/index.js",
"dev": "nodemon src/index.ts",
"build": "rimraf dist && tsc",
"lint": "eslint ."
}
Also, create a simple nodemon.json file in the root for smoother dev experience:
{
"watch": ["src"],
"ext": ".ts,.js",
"ignore": [],
"exec": "ts-node ./src/index.ts"
}
6. Git Ignore
Create a .gitignore file:
node_modules
dist
.env
How to Run
- Start MongoDB: Ensure your MongoDB instance is running locally or update the
.env file with your Atlas connection string.
- Develop: Run
npm run dev. The server will start on port 3000 and auto-restart on changes.
- Build for Production: Run
npm run build.
- Start Production: Run
npm start.
Testing the API
- POST
http://localhost:3000/api/users
- Body:
{ "name": "John Doe", "email": "john@example.com" }
- GET
http://localhost:3000/api/users