0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use Environment Variables in NestJS: Simple Guide

In NestJS, use the @nestjs/config package to load environment variables from a .env file. Import ConfigModule in your root module and access variables via ConfigService in your components.
๐Ÿ“

Syntax

To use environment variables in NestJS, first import ConfigModule in your root module with ConfigModule.forRoot(). Then inject ConfigService where you need access to variables. Use configService.get('VARIABLE_NAME') to read values.

  • ConfigModule.forRoot(): Loads variables from .env file automatically.
  • ConfigService: Provides access to environment variables.
  • get() method: Retrieves the value of a variable by name.
typescript
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

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

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

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

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

Example

This example shows how to load environment variables from a .env file and use them in a service to print the database host.

typescript
// .env file content
DATABASE_HOST=localhost
DATABASE_PORT=5432

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

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

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

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

  printDatabaseHost(): string {
    const host = this.configService.get<string>('DATABASE_HOST');
    return `Database host is: ${host}`;
  }
}

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AppService } from './app.service';

async function bootstrap() {
  const app = await NestFactory.createApplicationContext(AppModule);
  const appService = app.get(AppService);
  console.log(appService.printDatabaseHost());
  await app.close();
}
bootstrap();
Output
Database host is: localhost
โš ๏ธ

Common Pitfalls

1. Forgetting to call ConfigModule.forRoot() in the root module: Without this, environment variables won't load from the .env file.

2. Accessing variables before the module is initialized: Always inject ConfigService properly via constructor.

3. Typo in variable names: Environment variable names are case-sensitive and must match exactly.

4. Not creating a .env file or placing it in the wrong directory: The .env file should be in the project root.

typescript
/* Wrong: Missing ConfigModule.forRoot() */
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

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

/* Right: Import ConfigModule.forRoot() */
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

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

Quick Reference

StepDescription
1Create a .env file in your project root with key=value pairs.
2Import ConfigModule.forRoot() in your root module.
3Inject ConfigService in your classes via constructor.
4Use configService.get('VARIABLE_NAME') to read variables.
5Restart your app after changing .env to reload variables.
โœ…

Key Takeaways

Always import ConfigModule.forRoot() once in your root module to load .env variables.
Use ConfigService injected via constructor to access environment variables safely.
Keep your .env file in the project root and restart the app after changes.
Variable names are case-sensitive and must match exactly in your code and .env file.
Avoid accessing environment variables before NestJS initializes ConfigModule.