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:
npm install --save @nestjs/config
if you're one of those yarn people π§Ά)
yarn add @nestjs/config
π Step 2: Create Your .env
File β
In the root of your project, whisper your secrets:
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:
echo ".env" >> .gitignore
π§© Step 3: Load Config in AppModule β
Time to let NestJS read those sticky notes:
// 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) β
// 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 β
Task | Command/Code |
---|---|
Install config | npm install @nestjs/config |
Add .env file | PORT=3000 , etc. |
Load globally | ConfigModule.forRoot({ isGlobal: true }) |
Use anywhere | configService.get('KEY') |