Environment variables are values that change depending on the environment your app is running inβdevelopment, production, or testing.
Instead of manually changing values like your MongoDB URL each time you switch environments (which is not a good practice), weβll create a clean and scalable way to manage this using TypeScript.
π§ Why Do We Need Environment Variables?
Letβs say youβre using the following MongoDB URL for development:
mongodb+srv://username:<password>@cluster.mongodb.net/
But when your project is deployed to production, the URL changes.
Manually editing the code every time is error-prone.
β Solution: Use environment-based config files!
π οΈ Step-by-Step Guide
πΉ Step 1: Create Environment Files
Inside your project src/
folder, create a new folder named:
src/environments
Inside that folder, create the following three files:
π environments/ βββ dev.env.ts βββ prod.env.ts βββ env.ts
π dev.env.ts
import { Environment } from ‘./env’; export const DevEnvironment: Environment = { db_url: “mongodb+srv://username:<password>@cluster.mongodb.net/?retryWrites=true&w=majority&appName=Cluster” };
π prod.env.ts
import { Environment } from ‘./env’; export const ProdEnvironment: Environment = { db_url: “mongodb+srv://username:<password>@cluster.mongodb.net/?retryWrites=true&w=majority&appName=Cluster” };
π env.ts
This file decides which environment config to use.
import { ProdEnvironment } from ‘./prod.env’; import { DevEnvironment } from ‘./dev.env’; export interface Environment { db_url: string; } export function getEnvironmentVariables(): Environment { if (process.env.NODE_ENV === ‘production’) { return ProdEnvironment; } return DevEnvironment; }
π§© Step 2: Update index.ts
import * as express from ‘express’; import * as mongoose from ‘mongoose’; import { getEnvironmentVariables } from ‘./environments/env’; const app: express.Application = express(); app.listen(5000, () => { console.log(‘π Server is running at port 5000’); }); const DB_URI = getEnvironmentVariables().db_url; console.log(‘Mongo URI:’, DB_URI); mongoose.connect(DB_URI, { dbName: ‘test’ }) .then(() => console.log(‘β MongoDB connected successfully’)) .catch(err => { console.error(‘β MongoDB connection error:’, err.message); process.exit(1); }); // Optional: Debugging Events mongoose.connection.on(‘connected’, () => { console.log(‘Mongoose connected to DB’); }); mongoose.connection.on(‘error’, (err) => { console.log(‘Mongoose connection error:’, err); }); mongoose.connection.on(‘disconnected’, () => { console.log(‘Mongoose disconnected’); });
π§Ύ Final Project Structure
nodejs-project/ βββ node_modules/ βββ src/ β βββ environments/ β β βββ dev.env.ts β β βββ env.ts β β βββ prod.env.ts β βββ index.ts βββ package.json βββ package-lock.json βββ tsconfig.json
π» Run the Project
In your terminal, use:
npm start
Make sure to set the environment before running:
NODE_ENV=production npm start # or for dev NODE_ENV=development npm start
πΊ Terminal Output (Simulation)
sh
> npm start
> node dist/index.js
π Server is running at port 5000
Mongo URI: mongodb+srv://username:<password>@cluster.mongodb.net/?retryWrites=true&w=majority&appName=Cluster
β
MongoDB connected successfully
Mongoose connected to DB
π§ Bonus: Concept Diagram
Here’s a visual representation of how it works:
ββββββββββββββββββββββββββββββ β NODE_ENV = production β ββββββββββββββ¬βββββββββββββββ β βΌ βββββββββββββββββββββββ β getEnvironment β β (env.ts logic) β ββββββββββ¬βββββββββββββ β βββββββββββββββ΄βββββββββββββββ β β βΌ βΌ prod.env.ts dev.env.ts (db_url = PROD) (db_url = DEV)
Summary
-
Environment variables help keep your app clean and secure.
-
Use
.env.ts
pattern for type-safe environment config in TypeScript. -
Switch environments using
NODE_ENV
.