dev_tools
Back to guides

Express.js + TypeScript + MongoDB

Build a robust REST API using Express, TypeScript, and MongoDB with best practices.

Express
TypeScript
MongoDB
Node.js
Backend
1

Initialize Project

Create a new directory and initialize package.json. See npm init utils.

mkdir my-express-api && cd my-express-api && npm init -y
2

Install Dependencies

Install core libraries: Express (framework), Mongoose (ORM), dotenv (env vars), cors (CORS), and helmet (security headers).

npm install express mongoose dotenv cors helmet
3

Install Dev Dependencies

Install development tools: TypeScript, type definitions (@types/*), and ts-node-dev for hot-reloading.

npm install -D typescript @types/node @types/express @types/cors ts-node-dev
4

Initialize TypeScript

Generate a tsconfig.json file properly configured for Node.js development.

npx tsc --init
5

Configure tsconfig.json

Update tsconfig.json to strictly type your code and output to the ./dist directory. See tsconfig ref.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
6

Create Server File

Create the entry point src/index.ts with a basic Express app setup and MongoDB connection.

src/index.ts
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;

app.use(helmet());
app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
  res.json({ message: 'API is running' });
});

mongoose.connect(process.env.MONGODB_URI!)
  .then(() => {
    console.log('Connected to MongoDB');
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
  })
  .catch(console.error);
7

Create .env File

Define environment variables. Ensure MONGODB_URI points to your database instance.

.env
PORT=3000
MONGODB_URI=mongodb://localhost:27017/myapp
8

Add Scripts to package.json

Add dev, build, and start scripts to run your application.

package.json
"scripts": {
  "dev": "ts-node-dev --respawn --transpile-only src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js"
}
9

Start Development Server

Run the development server with hot-reloading.

npm run dev
💡Server should start on http://localhost:3000

Found this guide helpful? Check out more tools and guides.

Browse All Guides