0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use Config Module in NestJS: Simple Setup and Usage

In NestJS, use the ConfigModule to load and manage environment variables by importing it in your root module with ConfigModule.forRoot(). Access configuration values anywhere by injecting ConfigService into your classes.
๐Ÿ“

Syntax

The ConfigModule is imported in the root module using ConfigModule.forRoot(). This loads environment variables from a .env file by default. To access these variables, inject ConfigService in your components and use get() method with the variable name.

  • ConfigModule.forRoot(): Loads config globally.
  • ConfigService: Service to read config values.
  • get(key: string): Method to get a config value by key.
typescript
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

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

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

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

  getDatabaseHost() {
    return this.configService.get<string>('DATABASE_HOST');
  }
}
๐Ÿ’ป

Example

This example shows how to set up the ConfigModule to load environment variables from a .env file and access them in a service.

typescript
/* .env file content (place in project root):
DATABASE_HOST=localhost
DATABASE_PORT=5432
*/

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

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

// database.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

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

  getConnectionInfo() {
    const host = this.configService.get<string>('DATABASE_HOST');
    const port = this.configService.get<string>('DATABASE_PORT');
    return `Connecting to DB at ${host}:${port}`;
  }
}

// main.ts (for demonstration)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DatabaseService } from './database.service';

async function bootstrap() {
  const app = await NestFactory.createApplicationContext(AppModule);
  const dbService = app.get(DatabaseService);
  console.log(dbService.getConnectionInfo());
  await app.close();
}
bootstrap();
Output
Connecting to DB at localhost:5432
โš ๏ธ

Common Pitfalls

  • Not calling ConfigModule.forRoot() in the root module causes config not to load.
  • Forgetting to add ConfigModule to imports array means ConfigService won't be available.
  • Trying to access config keys that don't exist returns undefined, so always check or provide defaults.
  • Not placing the .env file in the project root or misnaming it causes variables not to load.
typescript
/* Wrong usage: Missing ConfigModule.forRoot() */
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule], // Missing forRoot()
})
export class AppModule {}

/* Right usage: */
@Module({
  imports: [ConfigModule.forRoot()],
})
export class AppModule {}
๐Ÿ“Š

Quick Reference

Summary tips for using ConfigModule in NestJS:

  • Import ConfigModule.forRoot() once in the root module.
  • Use ConfigService to access environment variables safely.
  • Place your .env file in the project root.
  • Use get() method with the exact key name.
  • Provide default values or validation if needed.
โœ…

Key Takeaways

Always import ConfigModule.forRoot() in your root module to load environment variables.
Inject ConfigService to access configuration values anywhere in your app.
Place your .env file in the project root for automatic loading.
Use configService.get('KEY') to read environment variables safely.
Check for undefined values and provide defaults to avoid runtime errors.