ConfigModule Basics

Preview — 3 of 10 questions

You import ConfigModule.forRoot({ isGlobal: true }) once in your AppModule. What does isGlobal: true change?

javascript
// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}
AIt registers ConfigService once so every other module can inject it without importing ConfigModule again
BIt loads the .env file from the operating system root directory instead of the project root
CIt makes every environment variable writable at runtime via ConfigService.set()
DIt forces the application to crash if any environment variable is missing

Given DATABASE_HOST=localhost in your .env, which call returns the value through the recommended API?

javascript
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class DbConfig {
  constructor(private readonly config: ConfigService) {}

  get host(): string {
    return this.config.get('DATABASE_HOST') ?? '127.0.0.1';
  }
}
AconfigService.read('DATABASE_HOST')
BconfigService.get('DATABASE_HOST')
CconfigService.env('DATABASE_HOST')
DconfigService.fetch('DATABASE_HOST')

What is the main advantage of using ConfigService.get() over reading process.env directly?

javascript
// Hard to test:
const port = Number(process.env.PORT);

// Injectable and mockable:
const port = this.config.get<number>('PORT', 3000);
Aprocess.env is unavailable in NestJS because Nest sandboxes Node globals
Bprocess.env is asynchronous and can block the event loop
CConfigService reads from a database while process.env reads from memory
DConfigService centralizes access, supports typed getters, default values, and validated/loaded config, making it testable and injectable

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.