configService.get('database.host') after the module loads?import { ConfigModule, ConfigService } from '@nestjs/config'; // config/database.config.ts export default () => ({ database: { host: 'localhost', port: 5432 } }); // app.module.ts import { Module } from '@nestjs/common'; @Module({ imports: [ConfigModule.forRoot({ load: [require('./config/database.config').default] })], }) export class AppModule {} // some.service.ts import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; @Injectable() export class SomeService { constructor(private configService: ConfigService) {} getDbHost() { return this.configService.get('database.host'); } }
The ConfigModule.forRoot loads the configuration from the function exported by database.config.ts. The returned object has a database key with a nested host property. So, configService.get('database.host') correctly accesses the nested value 'localhost'.
app.config.ts that exports a default function returning an object. Which import and usage in ConfigModule.forRoot is correct?The load option requires an array of functions that return configuration objects. Using require('./config/app.config').default correctly imports the default exported function. Options B and D use dynamic import incorrectly, and C passes a string instead of a function.
settings.config.ts:
export default () => {
return {
apiKey: process.env.API_KEY,
timeout: parseInt(process.env.TIMEOUT)
}
}
When running the app, it crashes with TypeError: Cannot read property 'API_KEY' of undefined. What is the cause?The error happens because process.env is undefined at the time the config function runs. This usually means environment variables were not loaded yet. NestJS config module loads environment variables from .env files only if envFilePath is set or ignoreEnvFile is false. Without loading env vars first, process.env is undefined.
configService.get('feature.enabled') after this config loads?feature.config.ts:
export default () => ({
feature: {
enabled: process.env.FEATURE_ENABLED === 'true'
}
});
And the environment variable FEATURE_ENABLED is not set, what does configService.get('feature.enabled') return?If process.env.FEATURE_ENABLED is undefined, then undefined === 'true' is false. So the enabled property is false.
In NestJS, custom config files export functions that return plain objects. The ConfigModule merges all loaded config objects into a single configuration object accessible via ConfigService. This allows modular and layered configuration.