Introduction
Configuration management helps keep your app settings organized and easy to change without breaking your code.
Configuration management helps keep your app settings organized and easy to change without breaking your code.
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true })], }) export class AppModule {}
ConfigModule.forRoot() to load environment variables and config files.isGlobal: true makes config available everywhere without importing again.ConfigModule.forRoot();
ConfigModule.forRoot({ isGlobal: true });ConfigModule.forRoot({ envFilePath: '.custom.env' });This example shows how to set up configuration globally and access a setting called DATABASE_HOST with a default fallback.
import { Module, Injectable } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Injectable() class AppService { constructor(private configService: ConfigService) {} getDatabaseHost(): string { return this.configService.get<string>('DATABASE_HOST', 'localhost'); } } @Module({ imports: [ConfigModule.forRoot({ isGlobal: true })], providers: [AppService], }) export class AppModule {} // Usage example (not part of module): // const appService = new AppService(new ConfigService()); // console.log(appService.getDatabaseHost());
Always keep sensitive info like API keys in environment variables, not in code.
Use different .env files for different environments to avoid mistakes.
ConfigService helps you safely get config values with optional defaults.
Configuration management keeps app settings organized and safe.
It helps you change settings without touching code.
NestJS provides ConfigModule and ConfigService to handle this easily.
getDatabaseHost() if the environment variable DATABASE_HOST is set to 'db.example.com'?
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class DatabaseService {
constructor(private configService: ConfigService) {}
getDatabaseHost(): string {
return this.configService.get<string>('DATABASE_HOST', 'localhost');
}
}@Injectable()
export class DatabaseService {
constructor(private configService: ConfigService) {}
getPort(): number {
return this.configService.get<number>('PORT');
}
}
Options:Pass the test and this pattern moves unknown