DEV Community

SHAHNAWAZ SAZID
SHAHNAWAZ SAZID

Posted on

Setting Up a TypeScript + Express + MongoDB(Mongoose) Backend from Scratch

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 
Enter fullscreen mode Exit fullscreen mode

This command creates a package.json file with default settings.

βš™οΈ 2. Install Core Dependencies

npm install express mongoose dotenv cors 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

In the generated tsconfig.json, update the following two lines:

"rootDir": "./src", "outDir": "./dist", 
Enter fullscreen mode Exit fullscreen mode

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" } 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

🌐 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 
Enter fullscreen mode Exit fullscreen mode

πŸ“ 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 
Enter fullscreen mode Exit fullscreen mode

πŸ’» 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}`); }); 
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 9. Build and Run the Project

npm run build npm start 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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! πŸ’™

Top comments (0)