Consider this NestJS module setup:
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true })],
})
export class AppModule {}What happens when the app starts?
Think about what isGlobal: true means in ConfigModule.
Setting isGlobal: true in ConfigModule.forRoot() loads environment variables from a .env file and makes the ConfigService available throughout the app without needing to import it in every module.
Given the ConfigService is injected, which code snippet correctly gets the DATABASE_URL variable?
constructor(private configService: ConfigService) {}
getDbUrl() {
// Which line is correct?
}Check the official method to get env variables from ConfigService.
The ConfigService provides a get() method to retrieve environment variables by name. Using process.env directly is possible but not recommended in NestJS.
Look at this code snippet:
ConfigModule.forRoot({
envFilePath: '.env.production',
isGlobal: true,
});The app does not load variables from .env.production. What is the likely cause?
Consider where the app runs and where the file is located.
The envFilePath is resolved relative to the current working directory when the app starts. If the file is not in that directory, the variables won't load. The other options are incorrect because isGlobal enables global access, and NestJS supports custom env file names.
Given this code:
ConfigModule.forRoot({
load: [() => ({
port: parseInt(process.env.PORT) || 3000,
mode: process.env.MODE || 'dev',
})],
isGlobal: true,
});
// Assume process.env.PORT = '0', process.env.MODE is undefined
const config = configService.get('port');What is the value of config?
Remember how parseInt and || work with 0.
parseInt('0') returns 0, which is falsy. Thus, parseInt(process.env.PORT) || 3000 evaluates to 3000. The loaded config sets port: 3000, so configService.get('port') returns 3000.
Choose the correct statement about environment-based configuration in NestJS.
Think about how to load different env files for development and production.
ConfigModule's envFilePath option can accept a function that returns different file paths based on process.env.NODE_ENV, allowing conditional loading of environment files. The other options are false: ConfigService does not auto-reload env files, variables do not require TypeScript interfaces, and ConfigModule can be global to avoid manual injection everywhere.