Environment variables help you keep important settings outside your code. This makes your app flexible and safe.
0
0
Environment variables in NestJS
Introduction
You want to keep secret keys like API tokens safe.
You need to change settings like database address without changing code.
You want to run the same app on your computer and on a server with different settings.
You want to avoid hardcoding values that might change later.
Syntax
NestJS
import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot()], }) export class AppModule {} // Accessing environment variable inside a class constructor(private configService: ConfigService) {} const value = this.configService.get<string>('VARIABLE_NAME');
Use ConfigModule.forRoot() to load variables from a .env file automatically.
Access variables using ConfigService.get() inside your classes.
Examples
This makes the config available everywhere without importing again.
NestJS
ConfigModule.forRoot({ isGlobal: true })Get the PORT variable, or use 3000 if not set.
NestJS
const port = this.configService.get<number>('PORT', 3000);
Put your environment variables in a
.env file at the project root.NestJS
DATABASE_URL=postgres://user:pass@localhost/dbname
# .env file exampleSample Program
This example shows how to load environment variables globally and access the DATABASE_URL variable inside a service.
NestJS
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true })], }) export class AppModule {} import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { constructor(private configService: ConfigService) {} getDatabaseUrl(): string { return this.configService.get<string>('DATABASE_URL') || 'No DB URL set'; } } // Assume .env file contains: // DATABASE_URL=postgres://user:pass@localhost/dbname
OutputSuccess
Important Notes
Always add your .env file to .gitignore to keep secrets safe.
You can define default values when accessing variables to avoid errors.
Use descriptive variable names to remember what each setting does.
Summary
Environment variables keep settings outside your code for safety and flexibility.
Use ConfigModule and ConfigService in NestJS to work with them easily.
Put variables in a .env file and load them with ConfigModule.forRoot().