Skip to content

Managing Config Across Environments — Because "dev" Isn't "prod", My Friend!

Welcome to the part where we teach our app to wear different hats depending on the party 🎩. Whether it's development, staging, or production — each environment deserves its own configuration.

🎭 Why Multi-Environment Config?

Imagine this:

  • In dev: You connect to a local DB and spam logs like crazy.
  • In prod: You connect to the real DB and whisper logs like a ninja. 🥷

You wouldn’t wear pajamas to a job interview, right? (Hopefully.)

🧪 Step 1: Create Multiple .env Files

In your project root, create these files:

.env
.env.development
.env.production
.env.staging

And fill them up with environment-specific configs:

env
# .env.development
PORT=3000
DEBUG=true
DB_URL=postgres://localhost/dev_db
env
# .env.production
PORT=80
DEBUG=false
DB_URL=postgres://prod_user:prod_pass@prod-db:5432/prod_db

🧠 Step 2: Tell NestJS to Be Smart About It

Update your ConfigModule to detect the right .env file:

ts
// app.module.ts
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: [`.env.${process.env.NODE_ENV}`, ".env"],
    }),
  ],
})
export class AppModule {}

With this, NestJS will first try to load .env.development if NODE_ENV=development. If not found, it’ll fall back to .env.

Neat, huh? 🤓

🔥 Step 3: Set NODE_ENV When Running the App

Depending on how you run your app, set NODE_ENV like this:

bash
NODE_ENV=production npm run start

Or use cross-env for compatibility (especially on Windows):

bash
npm install --save-dev cross-env

And in your package.json scripts:

json
"scripts": {
  "start:dev": "cross-env NODE_ENV=development nest start --watch",
  "start:prod": "cross-env NODE_ENV=production nest start"
}

🧪 BONUS: Use Config in Code

ts
const isDebug = this.configService.get("DEBUG") === "true";

Now your service logs like a chatty developer in dev, and goes silent like Batman in prod. 🦇

🧠 TL;DR

TaskDescription
.env filesCreate .env.development, .env.production, etc.
envFilePathSet in ConfigModule.forRoot()
NODE_ENVSet via CLI or script (NODE_ENV=prod)
Use ConfigService.get('KEY') to access values

Built by noobs, for noobs, with love 💻❤️