Skip to content

Adding .env & ConfigModule β€” Teaching Your App to Read Sticky Notes πŸ“ ​

So, you’ve got secrets to tell your app β€” like database passwords, API keys, and the name of your favorite pizza topping πŸ•. But hardcoding them? That’s a one-way ticket to πŸ’₯ chaos.

Enter the .env file: the Post-it note of your application's memory.

πŸ§™β€β™‚οΈ Step 1: Install the Magic Tools ​

NestJS doesn’t come with config powers out-of-the-box, so let’s install the helpers:

bash
npm install --save @nestjs/config

if you're one of those yarn people 🧢)

bash
yarn add @nestjs/config

πŸ“ Step 2: Create Your .env File ​

In the root of your project, whisper your secrets:

env
PORT=3000
DATABASE_URL=postgres://your_db_user:your_db_pass@localhost:5432/mydb
JWT_SECRET=shhh_dont_tell_anyone

Yes, it’s basically your app’s diary πŸ“–. Keep it out of Git with:

bash
echo ".env" >> .gitignore

🧩 Step 3: Load Config in AppModule ​

Time to let NestJS read those sticky notes:

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

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // so you don’t have to import it everywhere
    }),
  ],
})
export class AppModule {}

And poof πŸ’¨ β€” your app can now whisper its own secrets!

πŸ“š Step 4: Use It Anywhere (Like a Pro) ​

ts
// any.service.ts
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class AnyService {
  constructor(private configService: ConfigService) {
    const dbUrl = this.configService.get<string>("DATABASE_URL");
    console.log(`Connecting to: ${dbUrl}`);
  }
}

Like magic πŸͺ„, your app now reads .env without spilling the beans.

πŸ›‘ Bonus Tip: Validate Your Env Vars Like a Strict Teacher ✍️ ​

You can even use a schema validator like Joi to say:

"Hey app, I dare you to run without a JWT_SECRET!"

But we’ll save that for the "Advanced Config" chapter.

πŸ’‘ TL;DR ​

TaskCommand/Code
Install confignpm install @nestjs/config
Add .env filePORT=3000, etc.
Load globallyConfigModule.forRoot({ isGlobal: true })
Use anywhereconfigService.get('KEY')

Built by noobs, for noobs, with love πŸ’»β€οΈ