0
0
NestJSframework~5 mins

ConfigModule setup in NestJS

Choose your learning style9 modes available
Introduction

The ConfigModule helps your NestJS app read and manage settings easily. It keeps your app's configuration organized and safe.

You want to load environment variables like API keys or database URLs.
You need to share configuration settings across different parts of your app.
You want to keep sensitive data out of your code by using .env files.
You want to change settings without changing your code, like switching databases.
You want to validate your configuration to avoid errors.
Syntax
NestJS
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // optional
      envFilePath: '.env', // optional
      load: [configurationFunction], // optional
      validationSchema: Joi.object({}), // optional
    }),
  ],
})
export class AppModule {}

ConfigModule.forRoot() loads your config when the app starts.

Setting isGlobal: true makes config available everywhere without importing again.

Examples
Loads environment variables from a default .env file and makes config available locally.
NestJS
ConfigModule.forRoot()
Makes the config available in all modules without importing ConfigModule again.
NestJS
ConfigModule.forRoot({ isGlobal: true })
Loads environment variables from a custom file named .custom.env.
NestJS
ConfigModule.forRoot({ envFilePath: '.custom.env' })
Validates that DATABASE_URL is present and a string before app starts.
NestJS
ConfigModule.forRoot({
  validationSchema: Joi.object({
    DATABASE_URL: Joi.string().required(),
  }),
})
Sample Program

This example shows how to set up ConfigModule globally and use ConfigService to get a value.

NestJS
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

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

// Usage example in a service
import { Injectable } from '@nestjs/common';

@Injectable()
export class ExampleService {
  constructor(private configService: ConfigService) {}

  getDatabaseUrl(): string {
    return this.configService.get<string>('DATABASE_URL') || 'not set';
  }
}

// If .env contains DATABASE_URL=postgres://user:pass@localhost/db
// Then calling getDatabaseUrl() returns that string.
OutputSuccess
Important Notes

Always add a .env file to your .gitignore to keep secrets safe.

You can use validationSchema with Joi to catch missing or wrong config early.

Use ConfigService to access config values anywhere in your app.

Summary

ConfigModule helps manage app settings from environment variables.

Use forRoot() to load config and isGlobal: true to share it app-wide.

Access config values with ConfigService safely and easily.