Using .env files in Nest.js
When you are working with secrets (e.g., chatGPT API key) you may want to protect it. There is the less likely case where your serve is attacked and the information is stolen, and the more common situation: you send the key publicly to GitHub by accident; in the case of openAI, they block the key automatically. Never keep your keys at the frontend! Specially, Angular!
Here goes how you can use .env files in Nest.js. Those files are common practice when working with Node.js.
- Install a package
npm install --save @nestjs/config dotenv
2. Configurate your main module
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
ConfigModule.forRoot(), // Load .env file and make env variables available
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
3. Inject the service where you want to use environment variables
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private configService: ConfigService) {}
getPort(): number {
return this.configService.get<number>('PORT', 3000);
}
}
Closing lines
With this strategy, you protect your keys, secrets. Make sure your .gitignore files has .env file as ignore file, otherwise you will send it around, including, GitHub. When you are running unit testing, those files cannot be accessed from a unit testing level, just to let you know!
=
Source: in conversation with chatGPT