Creating boilerplate project
The user wants to create a boilerplate project for an Express, TypeScript, and MongoDB API. They likely need a folder structure, package.json, tsconfig, sample code, and environment configuration, with a focus on clarity. I should provide concise yet sufficient details for developers, including an overview, commands to initialize, necessary dependencies, basic app setup, database connection code, and a simple folder pattern for routes, models, and controllers, along with .env usage for environment variables.Structuring the boilerplate project
I could propose a project structure like this: a src folder with app.ts, server.ts, configuration, routes, controllers, and models, along with necessary files like .env.example, package.json, tsconfig.json, and nodemon.json for development. For scripts, I suggest including "build" and using "dev": with nodemon and ts-node for easier development. I want to add sample routes, like GET /health and /users, plus an explanation for the env variables, including process.env.MONGO_URI, along with ready-to-copy file contents and instructions for initialization.Defining project dependencies
For the project, I'll need several dependencies: "express," "mongoose," "dotenv," and possibly "cors" and "morgan." For devDependencies, I’ll include "typescript," "ts-node-dev" or "ts-node," and "nodemon." Actually, since Mongoose ships its own types (from version 5.11), there's no need for "@types/mongoose."
The tsconfig.json should specify settings like "outDir" as "dist," "rootDir" as "src," and "strict" as true. I plan to include a brief structure for files like server.ts, app.ts, and the configuration for Mongoose, along with a .env.example file for environment variables like MONGO_URI and PORT. I'll also present the contents of each file in concise code blocks. Below is a minimal, ready‑to‑copy boilerplate for an Express + TypeScript + MongoDB (Mongoose) API.
1. Initialize the project
mkdir express-ts-mongo-boilerplate
cd express-ts-mongo-boilerplate
npm init -y
Install dependencies:
npm install express mongoose dotenv cors
Dev dependencies:
npm install -D typescript ts-node-dev @types/express @types/node @types/cors
Initialize TypeScript:
npx tsc --init
2. Project structure
express-ts-mongo-boilerplate
├─ src
│ ├─ config
│ │ └─ db.ts
│ ├─ models
│ │ └─ user.model.ts
│ ├─ routes
│ │ ├─ index.ts
│ │ └─ user.routes.ts
│ ├─ controllers
│ │ └─ user.controller.ts
│ ├─ app.ts
│ └─ server.ts
├─ .env.example
├─ package.json
├─ tsconfig.json
└─ README.md (optional)
3. package.json
Replace the contents (or just merge the scripts):
{
"name": "express-ts-mongo-boilerplate",
"version": "1.0.0",
"main": "dist/server.js",
"license": "MIT",
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.0",
"express": "^4.21.0",
"mongoose": "^8.6.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/node": "^22.0.0",
"ts-node-dev": "^2.0.0",
"typescript": "^5.6.0"
}
}
(Version numbers are examples; use the latest.)
4. tsconfig.json
Replace the generated config with something like:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules"]
}
5. Environment file
.env.example
PORT=4000
MONGO_URI=mongodb://localhost:27017/express_ts_mongo
NODE_ENV=development
Copy this to .env and fill in real values:
cp .env.example .env
6. Database config
src/config/db.ts
import mongoose from 'mongoose';
const connectDB = async (): Promise<void> => {
const uri = process.env.MONGO_URI;
if (!uri) {
throw new Error('MONGO_URI is not defined in environment variables');
}
try {
await mongoose.connect(uri);
console.log('MongoDB connected');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
export default connectDB;
7. Express app setup
src/app.ts
import express, { Application } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import routes from './routes';
dotenv.config();
const app: Application = express();
// Middleware
app.use(cors());
app.use(express.json());
// Routes
app.use('/api', routes);
// Health check
app.get('/health', (_req, res) => {
res.json({ status: 'ok' });
});
export default app;
8. Server entry point
src/server.ts
import dotenv from 'dotenv';
import app from './app';
import connectDB from './config/db';
dotenv.config();
const PORT = process.env.PORT || 4000;
const startServer = async () => {
await connectDB();
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
};
startServer().catch((err) => {
console.error('Failed to start server:', err);
process.exit(1);
});
9. Basic model
src/models/user.model.ts
import mongoose, { Document, Schema } from 'mongoose';
export interface IUser extends Document {
name: string;
email: string;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>(
{
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true
}
},
{ timestamps: true }
);
const User = mongoose.model<IUser>('User', userSchema);
export default User;
10. Basic controller
src/controllers/user.controller.ts
import { Request, Response } from 'express';
import User from '../models/user.model';
export const getUsers = async (_req: Request, res: Response) => {
try {
const users = await User.find().lean();
res.json(users);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error' });
}
};
export const createUser = async (req: Request, res: Response) => {
try {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ message: 'name and email are required' });
}
const existing = await User.findOne({ email });
if (existing) {
return res.status(409).json({ message: 'Email already exists' });
}
const user = await User.create({ name, email });
res.status(201).json(user);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Server error' });
}
};
11. Routes
src/routes/user.routes.ts
import { Router } from 'express';
import { getUsers, createUser } from '../controllers/user.controller';
const router = Router();
router.get('/', getUsers);
router.post('/', createUser);
export default router;
src/routes/index.ts
import { Router } from 'express';
import userRoutes from './user.routes';
const router = Router();
router.use('/users', userRoutes);
export default router;
12. Run the project
Development (hot reload):
npm run dev
Build and run (production style):
npm run build
npm start
If you tell me your preferred style (e.g., repository URL layout, ESLint/Prettier, Jest tests), I can extend this boilerplate with those as well.