Generating directory structure
I need to outline a comprehensive directory structure for a project. It includes files like app.ts for the Express app and entry point in server.ts or index.ts. I'll also set up config files for environment variables, MongoDB connection, and routing. There will be controllers, models, middleware, utilities, and types as well. Additionally, I need to create a package.json and tsconfig.json file with essential scripts and configurations. It feels like a lot, but I want to deliver a complete boilerplate for this project!Preparing config file structure
I need to create a ready configuration file for the project. It’s important to make sure the TypeScript config targets Node 18 or the appropriate version. I should also include essential environment variables like MONGO_URI and PORT, along with error handling middleware. While I can't create the actual files, I can definitely outline their contents. It's crucial to focus on code correctness and organize the structure efficiently to make it straightforward for users!Proposing project structure
I want to outline a clear project structure for a boilerplate application using Express, TypeScript, and MongoDB. At the root, I'll have essential files like package.json, tsconfig.json, and .env.example, along with the src directory containing key components. This includes index.ts for server setup, app.ts for the Express app, and config files for loading environment variables and database connection.
I'll also list routes, controllers, models, and middlewares while keeping it concise and clear. It's important to suggest a user.routes.ts just as an example, even if it may not be needed!Installing and configuring dependencies
I need to outline steps for installing dependencies for the project. First, I’ll run commands to install Express, Mongoose, dotenv, and CORS, along with development dependencies like TypeScript and type declarations.
Next, I’ll provide the contents for a tsconfig.json file to set up TypeScript compilation options, ensuring it targets ES2020 and uses CommonJS modules. Then, I should add some minimal scripts to the package.json file for building and running the project.
Lastly, I'll include example version ranges for the dependencies based on the latest updates from 2024!Finalizing project files and instructions
I’m outlining the project files and their content. I'll specify dependencies with approximate versions and include a .env.example for environment variables. It feels right to require users to define MONGO_URI without a default for better practice, though I'll allow it for quick development. I need to sketch out each file, like index.ts to initialize the app, along with middlewares and routes.
I’ll create a gitignore file and possibly include a README snippet, while thinking about how to run the project with npm run dev. I want to ensure everything is adaptable for users!Creating boilerplate explanation
I need to prepare a clear and concise explanation for the user on how to use a provided boilerplate template. I’ll clarify that they can clone this structure for their projects. My outline will cover setup and dependencies, configuration files, the source structure, and instructions on how to run everything.
Each code snippet will have comments indicating file paths. I also want to ensure I'm using modern TypeScript practices for Mongoose, opting for InferSchemaType for better type safety while indicating that using Document is still acceptable. Let’s get this organized! Below is a minimal but structured boilerplate for an Express + TypeScript + MongoDB (Mongoose) API.
You can copy these files into a new folder and run the commands as indicated.
1. Initialize the project & install dependencies
mkdir express-ts-mongo-boilerplate
cd express-ts-mongo-boilerplate
npm init -y
# Runtime deps
npm install express mongoose dotenv cors
# Dev deps
npm install -D typescript ts-node-dev @types/express @types/node @types/cors
Initialize TypeScript config (we’ll overwrite it next):
npx tsc --init
2. Root-level config files
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"rootDir": "src",
"outDir": "dist",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
package.json (replace the generated one with something like this)
Update your package.json to at least have these fields (adjust name, version, etc. as you like):
{
"name": "express-ts-mongo-boilerplate",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"dev": "ts-node-dev --respawn --transpile-only src/index.ts",
"start": "node dist/index.js"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.0",
"express": "^4.18.2",
"mongoose": "^7.0.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^4.17.17",
"@types/node": "^18.0.0",
"ts-node-dev": "^2.0.0",
"typescript": "^5.0.0"
}
}
(Version ranges are examples; npm install will pick compatible versions.)
.env.example
PORT=3000
MONGO_URI=mongodb://localhost:27017/express-ts-mongo
NODE_ENV=development
Copy this to .env and adjust values when you run the project.
.gitignore
node_modules
dist
.env
3. Project structure
Create this structure:
src/
index.ts
app.ts
config/
env.ts
db.ts
routes/
index.ts
user.routes.ts
controllers/
user.controller.ts
models/
user.model.ts
middlewares/
errorHandler.ts
notFoundHandler.ts
Then add the contents below.
4. Source files
src/config/env.ts
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 3000;
const MONGO_URI =
process.env.MONGO_URI || 'mongodb://localhost:27017/express-ts-mongo';
const NODE_ENV = process.env.NODE_ENV || 'development';
export const config = {
PORT: Number(PORT),
MONGO_URI,
NODE_ENV
};
src/config/db.ts
import mongoose from 'mongoose';
import { config } from './env';
export async function connectDB(): Promise<void> {
try {
await mongoose.connect(config.MONGO_URI);
console.log('MongoDB connected');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
}
src/app.ts
import express, { Application } from 'express';
import cors from 'cors';
import router from './routes';
import { notFoundHandler } from './middlewares/notFoundHandler';
import { errorHandler } from './middlewares/errorHandler';
export function createApp(): Application {
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Health check
app.get('/health', (_req, res) => {
res.json({ status: 'ok' });
});
// API routes
app.use('/api', router);
// 404 handler
app.use(notFoundHandler);
// Error handler
app.use(errorHandler);
return app;
}
src/index.ts (entry point)
import { createApp } from './app';
import { config } from './config/env';
import { connectDB } from './config/db';
async function start() {
await connectDB();
const app = createApp();
app.listen(config.PORT, () => {
console.log(`Server listening on port ${config.PORT}`);
});
}
start().catch((error) => {
console.error('Failed to start server:', error);
process.exit(1);
});
src/routes/index.ts
import { Router } from 'express';
import userRouter from './user.routes';
const router = Router();
// Example resource
router.use('/users', userRouter);
export default router;
src/routes/user.routes.ts
import { Router } from 'express';
import * as userController from '../controllers/user.controller';
const router = Router();
router.get('/', userController.getUsers);
router.post('/', userController.createUser);
export default router;
src/controllers/user.controller.ts
import { Request, Response, NextFunction } from 'express';
import { User } from '../models/user.model';
export async function getUsers(
_req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
const users = await User.find();
res.json(users);
} catch (error) {
next(error);
}
}
export async function createUser(
req: Request,
res: Response,
next: NextFunction
): Promise<void> {
try {
const user = new User(req.body);
const saved = await user.save();
res.status(201).json(saved);
} catch (error) {
next(error);
}
}
src/models/user.model.ts
import { Schema, model, Document } 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
}
);
export const User = model<IUser>('User', userSchema);
src/middlewares/notFoundHandler.ts
import { Request, Response, NextFunction } from 'express';
export function notFoundHandler(
_req: Request,
res: Response,
_next: NextFunction
): void {
res.status(404).json({ message: 'Not found' });
}
src/middlewares/errorHandler.ts
import { Request, Response, NextFunction } from 'express';
export function errorHandler(
err: unknown,
_req: Request,
res: Response,
_next: NextFunction
): void {
console.error(err);
const status = 500;
const message =
err instanceof Error ? err.message : 'Internal server error';
res.status(status).json({ message });
}
5. Run the boilerplate
-
Create .env from .env.example and set MONGO_URI (e.g. local MongoDB).
-
Build and run:
# Development (auto-restart)
npm run dev
# Production build
npm run build
npm start
-
Test endpoints:
If you want, I can extend this with testing (Jest), ESLint/Prettier, or Docker configuration.