📖 Scenario: You are building a simple NestJS application that needs to read configuration values from environment variables. This is common when you want to change settings like the app port or database URL without changing the code.
🎯 Goal: Learn how to set up environment-based configuration in NestJS using the ConfigModule. You will create a configuration file, load environment variables, and access them in a service.
📋 What You'll Learn
Create a configuration file that exports a function returning an object with app settings
Import and configure the ConfigModule to load environment variables
Inject ConfigService into a service to read configuration values
Use the configuration values in the service logic
💡 Why This Matters
🌍 Real World
Many real-world NestJS apps need to change settings like ports, database URLs, or API keys without changing code. Environment-based configuration makes this easy and safe.
💼 Career
Understanding environment-based configuration is essential for backend developers working with NestJS, as it helps build flexible and secure applications that adapt to different deployment environments.
Progress0 / 4 steps
1
Create a configuration file
Create a file named app.config.ts that exports a default function returning an object with these exact properties: port set to 3000 and databaseUrl set to "mongodb://localhost:27017/myapp".
NestJS
Hint
This file returns an object with your app settings. Use export default () => ({ ... }).
2
Import ConfigModule with your config
In app.module.ts, import ConfigModule from @nestjs/config and configure it with ConfigModule.forRoot({ load: [appConfig] }). Also, import your app.config.ts as appConfig.
NestJS
Hint
Use ConfigModule.forRoot with the load option to load your config function.
3
Inject ConfigService in a service
Create a service named AppService that injects ConfigService from @nestjs/config in its constructor. Store it in a private readonly property named configService.
NestJS
Hint
Use constructor injection with private readonly configService: ConfigService.
4
Use configuration values in the service
Add a method getPort() in AppService that returns the port value from configService.get<number>('port'). Also add a method getDatabaseUrl() that returns the databaseUrl string from configService.get<string>('databaseUrl').
NestJS
Hint
Use configService.get<type>('key') to read config values.
Practice
(1/5)
1. What is the main purpose of using environment-based configuration in a NestJS application?
easy
A. To write more complex code logic
B. To hardcode all secrets inside the source files
C. To increase the size of the application
D. To change app settings without modifying the code
Hint: ConfigService.get returns env var value [OK]
Common Mistakes:
Expecting the key name instead of its value
Assuming undefined if variable exists
Confusing null with undefined
4. You wrote this code to load environment variables in NestJS:
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?
medium
A. You must call ConfigService.get() inside main.ts only
B. You forgot to create a .env file or set environment variables
C. You need to import HttpModule as well
D. ConfigModule.forRoot() should be called inside a service, not module
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 B
Quick Check:
Missing .env file = undefined env vars [OK]
Hint: Always create .env file or set env vars [OK]
Common Mistakes:
Thinking ConfigModule.forRoot() is misplaced
Assuming HttpModule is needed for config
Calling ConfigService.get() only in main.ts
5. You want to load different database URLs for development and production in NestJS using environment variables. Which approach correctly uses ConfigModule to load .env.development or .env.production based on NODE_ENV?
hard
A. ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` })
B. ConfigModule.forRoot({ envFilePath: '.env' })
C. ConfigModule.forRoot({ envFilePath: '.env.production' }) always
D. ConfigModule.forRoot({ envFilePath: '.env.development' }) always
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 A