CodePark/ questions / Configuration & lifecycle hooks
START PRACTICINGPRACTICE
Backend question · NestJS › Configuration & lifecycle hooks

How do you load environment variables with @nestjs/config and read them in a service?

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}

@Injectable()
export class MailService {
  constructor(private config: ConfigService) {}
  host = this.config.get<string>("SMTP_HOST", "localhost");
}

Import ConfigModule.forRoot(), then inject ConfigService and call get().

Loading. By default, ConfigModule.forRoot() loads a .env file from the project root. It merges the values with process.env and exposes them through ConfigService. Variables already set in the real environment win over the .env file. Useful options:

  • envFilePath points at other .env files.
  • isGlobal: true makes ConfigService injectable everywhere. You don't need to import ConfigModule in each module.

Reading. In a service, inject ConfigService and call get("KEY"). You can pass a default value. getOrThrow() throws at once when a required value is missing.

Structured config. You can pass factory functions with load: [factory], or use registerAs() namespaces. Then you read nested values like config.get("database.host").

  • ConfigModule.forRoot() loads .env into ConfigService.
  • Real environment variables override .env values.
  • isGlobal: true means you don't import it in every module.
  • Use get() with a default, and getOrThrow() for required values.
  • Use load or registerAs for structured config.