In this post, we will go through on how to build a modern Node.js application using TypeScript, Express.js, and MongoDB Atlas, following a modular folder structure. We’ll also integrate dotenv
for managing environment variables and use ts-node-dev
for a smooth development workflow.
✅ Step 1: Initialize Your Project
Create a new directory and initialize a Node.js project:
mkdir my-node-app && cd my-node-app
npm init -y
✅ Step 2: Set Up TypeScript
Install TypeScript and initialize the configuration:
npm install --save-dev typescript
npx tsc --init
Now, open the generated tsconfig.json
and update the following properties:
{
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"target": "es6",
"module": "commonjs"
}
✅ Step 3: Project Structure
Create a modular folder structure:
mkdir src
touch src/server.ts
We’ll build everything inside the src/
directory.
✅ Step 4: Install Core Dependencies
Install essential packages:
npm install mongodb express mongoose cors dotenv
Install type definitions for TypeScript:
npm install --save-dev @types/express @types/cors
✅ Step 5: Enable Hot Reloading
Install ts-node-dev
to auto-reload the app when files change:
npm install --save-dev ts-node-dev
Update your package.json
scripts:
"scripts": {
"dev": "ts-node-dev --respawn --transpile-only src/server.ts"
}
✅ Step 6: Add Environment Configuration
Create a .env
file in the root directory:
PORT=3000
MONGODB_URI=mongodb+srv://<db_username>:<db_password>@primary-cluster.t9drt.mongodb.net/<db_name>?retryWrites=true&w=majority&appName=Primary-Cluster
Then, create a config
folder:
mkdir src/config
touch src/config/index.ts
Inside src/config/index.ts
:
import dotenv from 'dotenv';
dotenv.config();
export const PORT = process.env.PORT || 5000;
export const MONGODB_URI = process.env.MONGODB_URI as string;
✅ Step 7: Set Up the Server
Edit src/server.ts
:
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import { PORT, MONGODB_URI } from './config';
const app = express();
// Middlewares
app.use(cors());
app.use(express.json());
// Sample route
app.get('/', (_req, res) => {
res.send('API is running...');
});
// Connect to MongoDB and start server
mongoose
.connect(MONGODB_URI)
.then(() => {
console.log('Connected to MongoDB Atlas');
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
})
.catch((error) => {
console.error('MongoDB connection error:', error);
});
✅ Step 8: Run Your App
Use the script to start your development server:
npm run dev
If everything is set up properly, you’ll see:
Connected to MongoDB Atlas
Server is running on http://localhost:3000
This is a clean, modular Node.js app powered by TypeScript, Express, and MongoDB Atlas. This foundation is perfect for building scalable APIs with environment separation and type safety.