Bird
Raised Fist0
NestJSframework~20 mins

Environment variables in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Environment Variables Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does NestJS load environment variables?
Consider a NestJS application using the ConfigModule. What is the behavior when you import ConfigModule.forRoot() without any options?
NestJS
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [ConfigModule.forRoot()],
})
export class AppModule {}
AIt requires you to specify the path to the .env file explicitly or it won't load any variables.
BIt only loads environment variables from process.env and ignores any .env files.
CIt loads environment variables from a .env file in the project root by default.
DIt throws an error if no .env file is found in the project root.
Attempts:
2 left
💡 Hint
Think about the default behavior of ConfigModule.forRoot() in NestJS.
❓ state_output
intermediate
2:00remaining
What value does ConfigService return?
Given the following .env file and NestJS service code, what will be the output of the console.log?
NestJS
.env file content:
PORT=3000

Service code:
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

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

  printPort() {
    console.log(this.configService.get('PORT'));
  }
}
A3000
Bundefined
Cnull
DThrows an error because PORT is a number but get returns string
Attempts:
2 left
💡 Hint
Remember how ConfigService reads values from .env files.
📝 Syntax
advanced
2:00remaining
Which option correctly loads a custom .env file path?
You want to load environment variables from a file named '.env.production' instead of the default '.env'. Which ConfigModule import is correct?
AConfigModule.forRoot({ envFile: '.env.production' })
BConfigModule.forRoot({ path: '.env.production' })
CConfigModule.forRoot({ env_path: '.env.production' })
DConfigModule.forRoot({ envFilePath: '.env.production' })
Attempts:
2 left
💡 Hint
Check the exact option name for specifying the env file path in ConfigModule.
🔧 Debug
advanced
2:00remaining
Why does ConfigService.get() return undefined?
You have a .env file with API_KEY=abc123 but calling configService.get('API_KEY') returns undefined. What is the most likely cause?
NestJS
import { ConfigModule, ConfigService } from '@nestjs/config';

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

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

  getKey() {
    return this.configService.get('API_KEY');
  }
}
AYou must call configService.load() before using get().
BThe .env file is not in the project root or not loaded properly.
CConfigService.get() only works for variables starting with NEST_ prefix.
DAPI_KEY is a reserved keyword and cannot be accessed.
Attempts:
2 left
💡 Hint
Check the location and loading of the .env file.
🧠 Conceptual
expert
2:00remaining
What is the effect of setting isGlobal: true in ConfigModule.forRoot()?
In a large NestJS app, you use ConfigModule.forRoot({ isGlobal: true }). What does this change in how you use ConfigModule?
AConfigModule is automatically available in all modules without needing to import it again.
BConfigModule variables become global environment variables accessible outside the app.
CConfigModule disables caching of environment variables for every request.
DConfigModule requires manual import in every module despite isGlobal: true.
Attempts:
2 left
💡 Hint
Think about module imports and global scope in NestJS.

Practice

(1/5)
1. What is the main purpose of using environment variables in a NestJS application?
easy
A. To hardcode sensitive data like passwords in the source code
B. To write all configuration directly inside the main application file
C. To make the application run faster by avoiding configuration files
D. To keep configuration settings outside the code for security and flexibility

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    To keep configuration settings outside the code for security and flexibility -> Option D
  4. Quick Check:

    Environment variables = external safe config [OK]
Hint: Environment variables keep secrets out of code [OK]
Common Mistakes:
  • Hardcoding sensitive data inside source code
  • Confusing environment variables with regular variables
  • Thinking environment variables improve speed
2. Which of the following is the correct way to load environment variables in a NestJS app?
easy
A. Manually read .env file using fs module in every service
B. Use process.env directly without any module
C. Import ConfigModule with ConfigModule.forRoot() in the root module
D. Declare environment variables inside main.ts without ConfigModule

Solution

  1. Step 1: Identify NestJS recommended method

    NestJS uses ConfigModule.forRoot() to load .env files and provide ConfigService.
  2. 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.
  3. Final Answer:

    Import ConfigModule with ConfigModule.forRoot() in the root module -> Option C
  4. Quick Check:

    ConfigModule.forRoot() loads env [OK]
Hint: Use ConfigModule.forRoot() to load .env [OK]
Common Mistakes:
  • Reading .env manually everywhere
  • Ignoring ConfigModule and using process.env directly
  • Declaring env variables inside code files
3. Given this code snippet in a NestJS service:
constructor(private configService: ConfigService) {}

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

If the .env file contains DATABASE_HOST=localhost, what will getDbHost() return?
medium
A. undefined
B. localhost
C. DATABASE_HOST
D. null

Solution

  1. Step 1: Understand ConfigService.get() behavior

    ConfigService.get('DATABASE_HOST') reads the value of DATABASE_HOST from loaded environment variables.
  2. Step 2: Match with .env content

    The .env file sets DATABASE_HOST=localhost, so the method returns 'localhost'.
  3. Final Answer:

    localhost -> Option B
  4. Quick Check:

    ConfigService.get('DATABASE_HOST') = 'localhost' [OK]
Hint: ConfigService.get returns env value by key [OK]
Common Mistakes:
  • Expecting the key name instead of value
  • Assuming undefined if ConfigModule not imported
  • Confusing null with undefined
4. What is wrong with this NestJS module setup for environment variables?
@Module({
  imports: [ConfigModule],
})
export class AppModule {}
medium
A. ConfigModule is imported without calling forRoot(), so env variables won't load
B. ConfigModule should be imported in providers, not imports
C. ConfigModule requires a .json config file, not .env
D. ConfigModule must be imported twice to work

Solution

  1. Step 1: Check ConfigModule import syntax

    ConfigModule must be imported with forRoot() to load environment variables from .env file.
  2. Step 2: Identify error in code

    The code imports ConfigModule directly without forRoot(), so env variables won't be loaded.
  3. Final Answer:

    ConfigModule is imported without calling forRoot(), so env variables won't load -> Option A
  4. Quick Check:

    ConfigModule.forRoot() needed to load env [OK]
Hint: Always use ConfigModule.forRoot() to load env [OK]
Common Mistakes:
  • Importing ConfigModule without forRoot()
  • Placing ConfigModule in providers instead of imports
  • Thinking ConfigModule needs JSON config
5. You want to provide a default value for an environment variable PORT in NestJS if it is not set in the .env file. Which code snippet correctly achieves this in a service?
hard
A. const port = this.configService.get('PORT') || 3000;
B. const port = process.env.PORT ? 3000 : this.configService.get('PORT');
C. const port = this.configService.get('PORT', 3000);
D. const port = this.configService.get('PORT') && 3000;

Solution

  1. Step 1: Understand default value logic

    If PORT is undefined or empty, use 3000 as default. Logical OR (||) works for this.
  2. 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.
  3. Final Answer:

    const port = this.configService.get('PORT') || 3000; -> Option A
  4. Quick Check:

    Use || to set default value [OK]
Hint: Use || to set default if env variable missing [OK]
Common Mistakes:
  • Using && instead of || for default
  • Passing default value as second argument to get()
  • Reversing condition logic
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