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! π
Top comments (0)