If you're planning to build a scalable, type-safe Node.js backend, integrating Express, Mongoose, TypeScript, dotenv, and CORS, here's a clean and efficient way to set it up. We'll also configure a .env file and write some essential build scripts. Let's walk through the setup step by step!
🧱 1. Initialize the Project
npm init -y
This command creates a package.json file with default settings.
⚙️ 2. Install Core Dependencies
npm install express mongoose dotenv cors
These are the libraries we'll need for our application:
express: Minimal and flexible Node.js web framework.
mongoose: ODM for MongoDB.
dotenv: Loads environment variables from .env.
cors: Enables Cross-Origin Resource Sharing.
🛠️ 3. Install Dev Dependencies
npm install --save-dev typescript @types/node @types/express @types/cors
These packages are required for TypeScript support and type definitions:
typescript: The TS compiler.
@types/node, @types/express, @types/cors: Type declarations for Node.js, Express, and CORS.
📁 4. Initialize TypeScript
tsc --init
In the generated tsconfig.json, update the following two lines:
"rootDir": "./src",
"outDir": "./dist",
This ensures TypeScript will transpile source files from src/ to dist/.
🧪 5. Add Scripts to package.json
Inside your package.json, update the scripts section:
"scripts": {
"build": "tsc",
"start": "node ./dist/app.js",
"dev": "ts-node-dev --respawn src/app.ts"
}
The build command compiles TypeScript, and start runs the built JavaScript. If you’re using ts-node-dev for development, you can hot-reload using the dev script.
🔥 Install ts-node-dev if using the dev command:
npm install --save-dev ts-node-dev
🌐 6. Create the .env File
At the root of the project, create a .env file and add your environment variables:
PORT=5000
DATABASE_URL=mongodb URI
📝 Note: Replace sensitive credentials before committing. Add .env to .gitignore!
🧠 7. Basic Project Structure
Create your folder structure:
project-root/
│
├── src/
│ ├── app.ts
│ └── server.ts
│
├── dist/
├── .env
├── tsconfig.json
└── package.json
💻 8. Sample server.ts
// src/server.ts
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import cors from 'cors';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors());
app.use(express.json());
// MongoDB Connection
mongoose
.connect(process.env.DATABASE_URL as string)
.then(() => console.log("MongoDB connected"))
.catch((err) => console.error("MongoDB connection error:", err));
// Routes
app.get('/', (_req, res) => {
res.send('API is running...');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
🧪 9. Build and Run the Project
npm run build
npm start
Your server should now be live and connected to your MongoDB Atlas cluster!
🧼 Bonus Tips
Use ts-node-dev during development for hot reloading:
npm run dev
Always include .env in your .gitignore.
Use proper error handling middleware and structure routes/controllers separately for larger apps.
📌 Conclusion
You’ve now built a clean TypeScript backend setup using Express, Mongoose, dotenv, and CORS. This is a solid boilerplate for most backend projects — scalable, type-safe, and easy to maintain.
If you found this helpful, feel free to share it with your dev circle! 💙