Environment-based configuration helps your NestJS app use different settings for development, testing, and production without changing code.
Environment-based configuration in NestJS
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ envFilePath: '.env', isGlobal: true, }), ], }) export class AppModule {}
ConfigModule.forRoot() to load environment variables from a file.isGlobal: true to make config available everywhere without importing again.ConfigModule.forRoot({ envFilePath: '.env.development' })ConfigModule.forRoot({ envFilePath: ['.env.production', '.env'] })process.env.const dbHost = process.env.DB_HOST;
ConfigService to get environment variables safely inside services or controllers.import { ConfigService } from '@nestjs/config'; constructor(private configService: ConfigService) {} const dbHost = this.configService.get<string>('DB_HOST');
This example shows how to load environment variables from a .env file and use them inside a service with ConfigService. It prints the database connection info based on the environment settings.
import { Module, Injectable } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ envFilePath: '.env', isGlobal: true, }), ], providers: [DatabaseService], }) export class AppModule {} @Injectable() export class DatabaseService { constructor(private configService: ConfigService) {} getConnectionInfo() { const host = this.configService.get<string>('DB_HOST'); const port = this.configService.get<number>('DB_PORT'); return `Connecting to DB at ${host}:${port}`; } } // Assume .env file contains: // DB_HOST=localhost // DB_PORT=5432 // Usage example: const dbService = new DatabaseService(new ConfigService()); console.log(dbService.getConnectionInfo());
Always keep your .env files out of version control to protect secrets.
You can create multiple .env files for different environments like .env.test or .env.production.
Use ConfigService instead of process.env for better type safety and testing.
Environment-based configuration lets your app adapt settings without code changes.
Use ConfigModule and ConfigService in NestJS to manage environment variables.
Keep secrets safe and switch easily between development, testing, and production setups.
Practice
Solution
Step 1: Understand environment-based configuration
It allows changing settings like database URLs or API keys without changing the app code.Step 2: Identify the correct purpose
Changing settings without code changes helps adapt the app to different environments easily.Final Answer:
To change app settings without modifying the code -> Option DQuick Check:
Environment config = change settings without code [OK]
- Confusing config with code logic
- Assuming config increases app size
- Hardcoding secrets inside source files
Solution
Step 1: Recall NestJS modules for config
The ConfigModule is designed to load and manage environment variables.Step 2: Match module to purpose
HttpModule handles HTTP, DatabaseModule handles DB, LoggerModule handles logs, so ConfigModule is correct.Final Answer:
ConfigModule -> Option AQuick Check:
ConfigModule loads env variables [OK]
- Choosing unrelated modules like HttpModule
- Confusing ConfigModule with DatabaseModule
- Assuming LoggerModule manages config
constructor(private configService: ConfigService) {}
getDbHost() {
return this.configService.get('DATABASE_HOST');
}What will
getDbHost() return if the environment variable DATABASE_HOST is set to localhost?Solution
Step 1: Understand ConfigService.get()
This method returns the value of the environment variable key passed, here 'DATABASE_HOST'.Step 2: Check environment variable value
The variable DATABASE_HOST is set to 'localhost', so get() returns 'localhost'.Final Answer:
localhost -> Option CQuick Check:
ConfigService.get('DATABASE_HOST') = 'localhost' [OK]
- Expecting the key name instead of its value
- Assuming undefined if variable exists
- Confusing null with undefined
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}But your app crashes with an error saying environment variables are undefined. What is the likely cause?
Solution
Step 1: Check environment variable source
ConfigModule loads variables from .env file or system environment. If missing, variables are undefined.Step 2: Identify common mistake
Not having a .env file or not setting variables causes undefined values and app crash.Final Answer:
You forgot to create a .env file or set environment variables -> Option BQuick Check:
Missing .env file = undefined env vars [OK]
- Thinking ConfigModule.forRoot() is misplaced
- Assuming HttpModule is needed for config
- Calling ConfigService.get() only in main.ts
ConfigModule to load .env.development or .env.production based on NODE_ENV?Solution
Step 1: Understand dynamic env file loading
Using envFilePath with template string allows loading .env files based on NODE_ENV value.Step 2: Check options
ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` }) dynamically loads .env.development or .env.production depending on NODE_ENV, others load fixed files.Final Answer:
ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` }) -> Option AQuick Check:
Dynamic envFilePath = correct multi-env config [OK]
- Hardcoding envFilePath to one file always
- Not using process.env.NODE_ENV in path
- Assuming default .env handles all environments
Ready to prove it?
Pass the test and this pattern moves unknown
