The Config Module

One Place For Every Environment Variable

The Config Module

@nestjs/config loads .env files, exposes a typed ConfigService, and validates required vars at boot.

4 min read Level 2/5 #nestjs#config#env
What you'll learn
  • Install @nestjs/config and import ConfigModule.forRoot
  • Read values with ConfigService.get
  • Validate environment variables with Joi

Every real Nest app needs to read configuration from environment variables. @nestjs/config is the official module for that — it loads .env, exposes a ConfigService, and refuses to boot if required vars are missing.

Install & Register

npm i @nestjs/config joi
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

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

isGlobal: true means you do not have to re-import it in every feature module — ConfigService is available everywhere.

Reading Values

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

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

  getUrl(): string {
    return this.config.get<string>('DATABASE_URL', 'postgres://localhost/dev');
  }
}

The second argument to get is a default — handy in dev but never a substitute for real validation in prod.

Validating At Boot

import * as Joi from 'joi';

ConfigModule.forRoot({
  isGlobal: true,
  validationSchema: Joi.object({
    NODE_ENV: Joi.string().valid('development', 'production', 'test').required(),
    DATABASE_URL: Joi.string().uri().required(),
    JWT_SECRET: Joi.string().min(32).required(),
  }),
});

If a required var is missing or malformed, Nest throws on startup — far better than discovering it from a 3am pager alert.

Typed Config

For autocompletion, define a typed namespace and consume it via ConfigService<AppConfig, true> or a custom config factory. It is a small amount of plumbing that pays back every time you read a value.

Logging →