0
0
NestJSframework~5 mins

Environment-based configuration in NestJS

Choose your learning style9 modes available
Introduction

Environment-based configuration helps your NestJS app use different settings for development, testing, and production without changing code.

You want to connect to different databases depending on where your app runs.
You need to enable debugging only in development but not in production.
You want to keep secret keys safe and not hard-code them in your app.
You want to change API endpoints based on the environment automatically.
Syntax
NestJS
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.env',
      isGlobal: true,
    }),
  ],
})
export class AppModule {}
Use ConfigModule.forRoot() to load environment variables from a file.
Set isGlobal: true to make config available everywhere without importing again.
Examples
Load environment variables from a specific file for development.
NestJS
ConfigModule.forRoot({ envFilePath: '.env.development' })
Load variables from multiple files, with later files overriding earlier ones.
NestJS
ConfigModule.forRoot({ envFilePath: ['.env.production', '.env'] })
Access environment variables directly using process.env.
NestJS
const dbHost = process.env.DB_HOST;
Use ConfigService to get environment variables safely inside services or controllers.
NestJS
import { ConfigService } from '@nestjs/config';

constructor(private configService: ConfigService) {}

const dbHost = this.configService.get<string>('DB_HOST');
Sample Program

This example shows how to load environment variables from a .env file and use them inside a service with ConfigService. It prints the database connection info based on the environment settings.

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

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

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

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

// Assume .env file contains:
// DB_HOST=localhost
// DB_PORT=5432

// Usage example:
const dbService = new DatabaseService(new ConfigService());
console.log(dbService.getConnectionInfo());
OutputSuccess
Important Notes

Always keep your .env files out of version control to protect secrets.

You can create multiple .env files for different environments like .env.test or .env.production.

Use ConfigService instead of process.env for better type safety and testing.

Summary

Environment-based configuration lets your app adapt settings without code changes.

Use ConfigModule and ConfigService in NestJS to manage environment variables.

Keep secrets safe and switch easily between development, testing, and production setups.