Bird
Raised Fist0
NestJSframework~5 mins

Environment-based configuration in NestJS

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using environment-based configuration in a NestJS application?
easy
A. To write more complex code logic
B. To hardcode all secrets inside the source files
C. To increase the size of the application
D. To change app settings without modifying the code

Solution

  1. Step 1: Understand environment-based configuration

    It allows changing settings like database URLs or API keys without changing the app code.
  2. Step 2: Identify the correct purpose

    Changing settings without code changes helps adapt the app to different environments easily.
  3. Final Answer:

    To change app settings without modifying the code -> Option D
  4. Quick Check:

    Environment config = change settings without code [OK]
Hint: Think: config changes without touching code [OK]
Common Mistakes:
  • Confusing config with code logic
  • Assuming config increases app size
  • Hardcoding secrets inside source files
2. Which NestJS module is used to load environment variables for configuration?
easy
A. ConfigModule
B. DatabaseModule
C. HttpModule
D. LoggerModule

Solution

  1. Step 1: Recall NestJS modules for config

    The ConfigModule is designed to load and manage environment variables.
  2. Step 2: Match module to purpose

    HttpModule handles HTTP, DatabaseModule handles DB, LoggerModule handles logs, so ConfigModule is correct.
  3. Final Answer:

    ConfigModule -> Option A
  4. Quick Check:

    ConfigModule loads env variables [OK]
Hint: ConfigModule = environment variables loader [OK]
Common Mistakes:
  • Choosing unrelated modules like HttpModule
  • Confusing ConfigModule with DatabaseModule
  • Assuming LoggerModule manages config
3. Given this code snippet in a NestJS service:
constructor(private configService: ConfigService) {}

getDbHost() {
  return this.configService.get('DATABASE_HOST');
}

What will getDbHost() return if the environment variable DATABASE_HOST is set to localhost?
medium
A. DATABASE_HOST
B. undefined
C. localhost
D. null

Solution

  1. Step 1: Understand ConfigService.get()

    This method returns the value of the environment variable key passed, here 'DATABASE_HOST'.
  2. Step 2: Check environment variable value

    The variable DATABASE_HOST is set to 'localhost', so get() returns 'localhost'.
  3. Final Answer:

    localhost -> Option C
  4. Quick Check:

    ConfigService.get('DATABASE_HOST') = 'localhost' [OK]
Hint: ConfigService.get returns env var value [OK]
Common Mistakes:
  • Expecting the key name instead of its value
  • Assuming undefined if variable exists
  • Confusing null with undefined
4. You wrote this code to load environment variables in NestJS:
import { ConfigModule } from '@nestjs/config';

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

But your app crashes with an error saying environment variables are undefined. What is the likely cause?
medium
A. You must call ConfigService.get() inside main.ts only
B. You forgot to create a .env file or set environment variables
C. You need to import HttpModule as well
D. ConfigModule.forRoot() should be called inside a service, not module

Solution

  1. Step 1: Check environment variable source

    ConfigModule loads variables from .env file or system environment. If missing, variables are undefined.
  2. Step 2: Identify common mistake

    Not having a .env file or not setting variables causes undefined values and app crash.
  3. Final Answer:

    You forgot to create a .env file or set environment variables -> Option B
  4. Quick Check:

    Missing .env file = undefined env vars [OK]
Hint: Always create .env file or set env vars [OK]
Common Mistakes:
  • Thinking ConfigModule.forRoot() is misplaced
  • Assuming HttpModule is needed for config
  • Calling ConfigService.get() only in main.ts
5. You want to load different database URLs for development and production in NestJS using environment variables. Which approach correctly uses ConfigModule to load .env.development or .env.production based on NODE_ENV?
hard
A. ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` })
B. ConfigModule.forRoot({ envFilePath: '.env' })
C. ConfigModule.forRoot({ envFilePath: '.env.production' }) always
D. ConfigModule.forRoot({ envFilePath: '.env.development' }) always

Solution

  1. Step 1: Understand dynamic env file loading

    Using envFilePath with template string allows loading .env files based on NODE_ENV value.
  2. Step 2: Check options

    ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` }) dynamically loads .env.development or .env.production depending on NODE_ENV, others load fixed files.
  3. Final Answer:

    ConfigModule.forRoot({ envFilePath: `.env.${process.env.NODE_ENV}` }) -> Option A
  4. Quick Check:

    Dynamic envFilePath = correct multi-env config [OK]
Hint: Use template string with NODE_ENV for envFilePath [OK]
Common Mistakes:
  • Hardcoding envFilePath to one file always
  • Not using process.env.NODE_ENV in path
  • Assuming default .env handles all environments
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard