The user wants a boilerplate project for an API built with Express, TypeScript, and MongoDB.
1. Understand the Goal:
The goal is to provide a starting point (boilerplate) that saves the user time setting up the basic architecture. It needs to be clean, modular, and follow best practices.
2. Identify Key Components:
- Runtime/Platform: Node.js
- Framework: Express.js
- Language: TypeScript
- Database: MongoDB (specifically using Mongoose for object modeling is the standard approach).
- Architecture: A typical layered architecture (Controller -> Service -> Repository, or just Controller -> Service/Model depending on complexity). For a boilerplate, a Controller-Route-Model structure is usually sufficient but adding a Service layer is "cleaner." Let's stick to a modular structure: Routes, Controllers, Models, Middlewares, Config, Utils.
3. Determine Project Structure:
A good structure is crucial for a boilerplate.
src/
├── config/ # Environment variables and configuration
├── models/ # Mongoose models
├── routes/ # API route definitions
├── controllers/ # Request handling logic
├── middlewares/ # Custom middleware (auth, error handling)
├── utils/ # Helper functions
├── app.ts # Express app setup
└── server.ts # Entry point
4. Step-by-Step Implementation Plan:
- Step 0: Prerequisites: Node.js, MongoDB instance.
- Step 1: Initialization:
npm init, installing dependencies.
- Step 2: TypeScript Setup:
tsconfig.json, build scripts.
- Step 3: Database Connection: Setting up Mongoose.
- Step 4: Core App Logic: Creating the Express app instance, body parser, CORS.
- Step 5: Implementation Example: A simple "User" or "Item" CRUD to demonstrate the pattern.
- Step 6: Error Handling: A global error handler middleware (essential for production).
- Step 7: Environment Variables:
dotenv.
- Step 8: Scripts: Dev (nodemon), Build, Start.
5. Drafting the Code (Mental or Scratchpad):
-
Dependencies: express, mongoose, dotenv, cors.
-
Dev Dependencies: typescript, @types/express, @types/node, ts-node, nodemon.
-
tsconfig.json: Needs outDir, rootDir, strict: true.
-
Server.ts:
- Import
dotenv.
- Import
app from app.ts.
- Connect to DB.
- Listen on port.
-
App.ts:
- Import express, cors.
- Middleware: JSON parser, URL encoded.
- Routes:
/api/v1/...
- Error handler.
-
Model (e.g., Todo): Simple schema (title, completed).
-
Controller: Functions to get all, create, delete, etc.
6. Refining the Output:
I need to present this clearly. I will use:
- A file/folder tree structure.
- Code blocks for each essential file.
- Instructions on how to run it.
Self-Correction during thought process:
Should I add ESLint/Prettier? It makes the boilerplate heavier but is good practice. Decision: Keep it minimal for now, mention it as an optional next step. Focus on the core "Express + TS + Mongo" requirement.
Should I add authentication (JWT)? Decision: No, that complicates a basic boilerplate too much. Keep it focused on the stack setup, not business logic.
7. Finalizing the structure to present:
- package.json: Define dependencies.
- tsconfig.json: TS configuration.
- .env: Config vars.
- src/app.ts: Express configuration.
- src/server.ts: Entry point & DB connection.
- src/models/Todo.ts: Mongoose schema.
- src/routes/todoRoutes.ts: Routing.
- src/controllers/todoController.ts: Logic.
- src/middlewares/errorHandler.ts: Basic async error catching.
8. Constructing the response:
I will write out the file contents one by one, ensuring import paths are correct (e.g., ./models/Todo). I'll use ES6+ syntax and async/await.
Let's start writing the response based on this plan.
Here is a complete, production-ready boilerplate for an Express + TypeScript + MongoDB API.
This setup includes:
- TypeScript configured for Node.js.
- Mongoose for MongoDB object modeling.
- Dotenv for environment variable management.
- Nodemon for hot-reloading during development.
- A modular folder structure (Controller, Model, Route).
1. Project Initialization
Create a new folder and initialize the project:
mkdir express-ts-boilerplate
cd express-ts-boilerplate
npm init -y
2. Install Dependencies
Install the runtime dependencies:
npm install express mongoose dotenv cors
Install the development dependencies (TypeScript, types, and dev tools):
npm install -D typescript ts-node nodemon @types/node @types/express @types/mongoose @types/dotenv @types/cors
3. Project Structure
Create the following folder structure:
.
├── src/
│ ├── controllers/
│ │ └── userController.ts
│ ├── models/
│ │ └── userModel.ts
│ ├── routes/
│ │ ├── index.ts
│ │ └── userRoutes.ts
│ ├── app.ts
│ └── server.ts
├── .env
├── nodemon.json
├── package.json
└── tsconfig.json
4. Configuration Files
tsconfig.json
Configure TypeScript compilation options.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
nodemon.json
Configure Nodemon to watch .ts files and execute ts-node.
{
"watch": ["src"],
"ext": "ts",
"exec": "ts-node src/server.ts"
}
.env
Store your environment variables.
PORT=5000
MONGO_URI=mongodb://localhost:27017/my_database
NODE_ENV=development
5. The Code
src/app.ts
Sets up the Express application, middleware, and route mounting.
import express, { Application, Request, Response } from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import routes from './routes';
import dotenv from 'dotenv';
dotenv.config();
const app: Application = express();
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Database Connection
const MONGO_URI = process.env.MONGO_URI || '';
mongoose
.connect(MONGO_URI)
.then(() => console.log('✅ MongoDB Connected'))
.catch((err) => console.error('❌ MongoDB Connection Error:', err));
// Routes
app.use('/api', routes);
// Health Check
app.get('/', (req: Request, res: Response) => {
res.send('API is running...');
});
export default app;
src/server.ts
Starts the server.
import app from './app';
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});
src/models/userModel.ts
Defines the Mongoose schema.
import { Schema, model, Document } from 'mongoose';
export interface IUser extends Document {
name: string;
email: string;
password: string;
createdAt: Date;
}
const UserSchema: Schema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
},
{ timestamps: true }
);
export default model<IUser>('User', UserSchema);
src/controllers/userController.ts
Handles logic for requests.
import { Request, Response } from 'express';
import User from '../models/userModel';
export const getUsers = async (req: Request, res: Response): Promise<void> => {
try {
const users = await User.find();
res.status(200).json(users);
} catch (error: any) {
res.status(500).json({ message: error.message });
}
};
export const createUser = async (req: Request, res: Response): Promise<void> => {
try {
const user = new User(req.body);
const savedUser = await user.save();
res.status(201).json(savedUser);
} catch (error: any) {
res.status(400).json({ message: error.message });
}
};
src/routes/userRoutes.ts
Defines endpoints for the User resource.
import { Router } from 'express';
import { getUsers, createUser } from '../controllers/userController';
const router = Router();
router.get('/users', getUsers);
router.post('/users', createUser);
export default router;
src/routes/index.ts
Combines all routes.
import { Router } from 'express';
import userRoutes from './userRoutes';
const router = Router();
router.use('/', userRoutes);
export default router;
6. Scripts
Update your package.json to include run scripts:
"scripts": {
"dev": "nodemon",
"build": "tsc",
"start": "node dist/server.js"
}
7. Run the Project
To start the development server with hot-reload:
npm run dev
To build for production:
npm run build
npm start