Environment variables help you keep important settings outside your code. This makes your app flexible and safe.
Environment variables in 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.
ConfigModule.forRoot({ isGlobal: true })const port = this.configService.get<number>('PORT', 3000);
.env file at the project root.DATABASE_URL=postgres://user:pass@localhost/dbname
# .env file exampleThis example shows how to load environment variables globally and access the DATABASE_URL variable inside a service.
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
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.
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().
Practice
Solution
Step 1: Understand environment variables purpose
Environment variables store settings like API keys or database URLs outside the code to keep them safe and easy to change.Step 2: Compare options
Only To keep configuration settings outside the code for security and flexibility correctly describes this purpose. Options A and B suggest unsafe practices, and D is incorrect about performance.Final Answer:
To keep configuration settings outside the code for security and flexibility -> Option DQuick Check:
Environment variables = external safe config [OK]
- Hardcoding sensitive data inside source code
- Confusing environment variables with regular variables
- Thinking environment variables improve speed
Solution
Step 1: Identify NestJS recommended method
NestJS uses ConfigModule.forRoot() to load .env files and provide ConfigService.Step 2: Evaluate other options
Options A and C are possible but not recommended patterns. Declare environment variables inside main.ts without ConfigModule is incorrect because environment variables are external.Final Answer:
Import ConfigModule with ConfigModule.forRoot() in the root module -> Option CQuick Check:
ConfigModule.forRoot() loads env [OK]
- Reading .env manually everywhere
- Ignoring ConfigModule and using process.env directly
- Declaring env variables inside code files
constructor(private configService: ConfigService) {}
getDbHost() {
return this.configService.get('DATABASE_HOST');
}If the .env file contains
DATABASE_HOST=localhost, what will getDbHost() return?Solution
Step 1: Understand ConfigService.get() behavior
ConfigService.get('DATABASE_HOST') reads the value of DATABASE_HOST from loaded environment variables.Step 2: Match with .env content
The .env file sets DATABASE_HOST=localhost, so the method returns 'localhost'.Final Answer:
localhost -> Option BQuick Check:
ConfigService.get('DATABASE_HOST') = 'localhost' [OK]
- Expecting the key name instead of value
- Assuming undefined if ConfigModule not imported
- Confusing null with undefined
@Module({
imports: [ConfigModule],
})
export class AppModule {}Solution
Step 1: Check ConfigModule import syntax
ConfigModule must be imported with forRoot() to load environment variables from .env file.Step 2: Identify error in code
The code imports ConfigModule directly without forRoot(), so env variables won't be loaded.Final Answer:
ConfigModule is imported without calling forRoot(), so env variables won't load -> Option AQuick Check:
ConfigModule.forRoot() needed to load env [OK]
- Importing ConfigModule without forRoot()
- Placing ConfigModule in providers instead of imports
- Thinking ConfigModule needs JSON config
PORT in NestJS if it is not set in the .env file. Which code snippet correctly achieves this in a service?Solution
Step 1: Understand default value logic
If PORT is undefined or empty, use 3000 as default. Logical OR (||) works for this.Step 2: Analyze options
const port = this.configService.get('PORT') || 3000; uses || to provide default 3000 if get('PORT') is falsy. const port = process.env.PORT ? 3000 : this.configService.get('PORT'); reverses logic incorrectly. const port = this.configService.get('PORT', 3000); is invalid because get() does not take default param. const port = this.configService.get('PORT') && 3000; uses && which returns 3000 only if PORT is truthy, wrong logic.Final Answer:
const port = this.configService.get('PORT') || 3000; -> Option AQuick Check:
Use || to set default value [OK]
- Using && instead of || for default
- Passing default value as second argument to get()
- Reversing condition logic
Ready to prove it?
Pass the test and this pattern moves unknown
