The ConfigModule helps your NestJS app read and manage settings easily. It keeps your app's configuration organized and safe.
ConfigModule setup in NestJS
Introduction
Syntax
NestJS
import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, // optional envFilePath: '.env', // optional load: [configurationFunction], // optional validationSchema: Joi.object({}), // optional }), ], }) export class AppModule {}
ConfigModule.forRoot() loads your config when the app starts.
Setting isGlobal: true makes config available everywhere without importing again.
Examples
NestJS
ConfigModule.forRoot()
NestJS
ConfigModule.forRoot({ isGlobal: true })NestJS
ConfigModule.forRoot({ envFilePath: '.custom.env' })NestJS
ConfigModule.forRoot({
validationSchema: Joi.object({
DATABASE_URL: Joi.string().required(),
}),
})Sample Program
This example shows how to set up ConfigModule globally and use ConfigService to get a value.
NestJS
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), ], }) export class AppModule {} // Usage example in a service import { Injectable } from '@nestjs/common'; @Injectable() export class ExampleService { constructor(private configService: ConfigService) {} getDatabaseUrl(): string { return this.configService.get<string>('DATABASE_URL') || 'not set'; } } // If .env contains DATABASE_URL=postgres://user:pass@localhost/db // Then calling getDatabaseUrl() returns that string.
Important Notes
Always add a .env file to your .gitignore to keep secrets safe.
You can use validationSchema with Joi to catch missing or wrong config early.
Use ConfigService to access config values anywhere in your app.
Summary
ConfigModule helps manage app settings from environment variables.
Use forRoot() to load config and isGlobal: true to share it app-wide.
Access config values with ConfigService safely and easily.
Practice
1. What is the main purpose of
ConfigModule in a NestJS application?easy
Solution
Step 1: Understand ConfigModule role
The ConfigModule is designed to load and manage configuration settings, often from environment variables.Step 2: Compare with other options
Options A, B, and D relate to other parts of NestJS like database connections, HTTP handling, and middleware, not configuration management.Final Answer:
To manage application settings using environment variables -> Option AQuick Check:
ConfigModule = Manage app settings [OK]
Hint: ConfigModule is for app settings, not HTTP or DB [OK]
Common Mistakes:
- Confusing ConfigModule with database modules
- Thinking ConfigModule handles HTTP requests
- Assuming ConfigModule creates middleware
2. Which is the correct way to import
ConfigModule globally in the root module?easy
Solution
Step 1: Recall ConfigModule global setup syntax
To make ConfigModule available app-wide, useforRoot()withisGlobal: true.Step 2: Check other options for correctness
forFeature()is for scoped configs,register()andglobal()are not valid methods here.Final Answer:
ConfigModule.forRoot({ isGlobal: true }) -> Option CQuick Check:
Global config = forRoot + isGlobal true [OK]
Hint: Use forRoot with isGlobal true for global config [OK]
Common Mistakes:
- Using forFeature instead of forRoot
- Trying to use non-existent methods like global()
- Confusing register with forRoot
3. Given this code snippet in a NestJS service:
What will
constructor(private configService: ConfigService) {}
getDbHost() {
return this.configService.get('DATABASE_HOST');
}What will
getDbHost() return if DATABASE_HOST is set to "localhost" in the environment?medium
Solution
Step 1: Understand ConfigService.get behavior
Thegetmethod returns the value of the environment variable if set, here 'localhost'.Step 2: Check environment variable presence
SinceDATABASE_HOSTis set to 'localhost', the method returns that string, not undefined or null.Final Answer:
"localhost" -> Option DQuick Check:
Env var set = get returns value [OK]
Hint: get() returns env value if set, else undefined [OK]
Common Mistakes:
- Assuming get returns null if variable exists
- Expecting an error if variable is missing
- Confusing undefined with null
4. Identify the error in this NestJS module setup:
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
providers: [ConfigService],
})
export class AppModule {}medium
Solution
Step 1: Understand global ConfigModule behavior
WhenisGlobal: trueis set, ConfigService is automatically provided app-wide, no need to add it manually.Step 2: Check other options for validity
Importing ConfigService is not mandatory in module file, forRoot supports isGlobal, and ConfigModule belongs in imports array.Final Answer:
ConfigService should not be listed in providers when ConfigModule is global -> Option AQuick Check:
Global ConfigModule auto-provides ConfigService [OK]
Hint: Don't add ConfigService to providers if ConfigModule is global [OK]
Common Mistakes:
- Adding ConfigService to providers unnecessarily
- Thinking isGlobal is invalid option
- Placing ConfigModule in controllers array
5. You want to load a custom configuration file named
custom.env using ConfigModule and make it global. Which setup is correct?hard
Solution
Step 1: Identify correct option names for ConfigModule
The correct option to specify a custom env file isenvFilePath, and to make it global useisGlobal: trueinsideforRoot().Step 2: Eliminate incorrect options
envFileNameandglobalare invalid option names;forFeatureandregisterare not used for global config loading.Final Answer:
ConfigModule.forRoot({ envFilePath: 'custom.env', isGlobal: true }) -> Option BQuick Check:
Custom env + global = envFilePath + isGlobal true [OK]
Hint: Use envFilePath and isGlobal in forRoot for custom global config [OK]
Common Mistakes:
- Using envFileName instead of envFilePath
- Trying to use forFeature for global config
- Using register instead of forRoot
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
