Configuration with @nestjs/config
The ConfigModule loads environment variables and exposes them through an injectable ConfigService.
Syntax
this.configService.get('KEY')Hard-coding secrets and settings is a mistake. The @nestjs/config package loads values from .env files and environment variables and serves them through a ConfigService.
Setup
- Import
ConfigModule.forRoot()in the root module. AddisGlobal: trueso you can injectConfigServiceanywhere. - Inject
ConfigServiceand read values withget().
Keep a .env file out of version control and provide a .env.example template instead.
Example
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}
// Anywhere with DI:
// constructor(private config: ConfigService) {}
// const port = this.config.get<number>('PORT');When to use it
- A developer loads database credentials from a .env file using ConfigModule.forRoot() so the app never hard-codes secrets.
- A team uses a Joi validation schema in ConfigModule.forRoot({ validationSchema }) to fail fast at startup if required env vars are missing.
- An engineer injects ConfigService into a service and calls cfg.get<number>("PORT", 3000) to read typed config values with a safe default.
More examples
Load .env with ConfigModule
Registers ConfigModule as a global module that reads the .env file, making ConfigService injectable everywhere without repeated imports.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // no need to import in every module
envFilePath: '.env',
}),
],
})
export class AppModule {}Inject ConfigService
Injects ConfigService and reads DATABASE_URL with a fallback default, using TypeScript generics for a typed return value.
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private config: ConfigService) {}
getDatabaseUrl(): string {
return this.config.get<string>('DATABASE_URL', 'sqlite::memory:');
}
}Validate env vars with Joi
Passes a Joi schema to ConfigModule so the app throws an error at startup if any required environment variable is missing or invalid.
import * as Joi from 'joi';
ConfigModule.forRoot({
isGlobal: true,
validationSchema: Joi.object({
DATABASE_URL: Joi.string().uri().required(),
JWT_SECRET: Joi.string().min(32).required(),
PORT: Joi.number().default(3000),
}),
})
Discussion