configService.get('APP_NAME') inside AppService?import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [() => ({ APP_NAME: 'NestApp' })], }), ], providers: [ { provide: 'APP_SERVICE', useFactory: (configService: ConfigService) => { return { appName: configService.get('APP_NAME') }; }, inject: [ConfigService], }, ], exports: ['APP_SERVICE'], }) export class AppModule {}
ConfigModule.forRoot with isGlobal: true makes the config available everywhere.The ConfigModule is set as global and loads a config object with APP_NAME set to 'NestApp'. The ConfigService can access this value anywhere, so configService.get('APP_NAME') returns 'NestApp'.
.env.dev using ConfigModule. Which code snippet correctly sets this up?The correct option is envFilePath. This tells ConfigModule to load environment variables from the specified file.
configService.get('DATABASE_URL') return undefined?
Code:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [ConfigModule.forRoot()],
})
export class AppModule {}
And the environment file .env contains:
DATABASE_URL=postgres://user:pass@localhost/db
But configService.get('DATABASE_URL') returns undefined.By default, ConfigModule looks for .env in the current working directory. If the .env file is elsewhere, variables won't load, causing undefined results.
configService.get('API_KEY') return?
Code:
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [async () => {
return new Promise(resolve => {
setTimeout(() => resolve({ API_KEY: '12345' }), 100);
});
}],
}),
],
})
export class AppModule {}ConfigModule's load expects synchronous functions returning config objects. Async functions return promises, so config keys are not set, resulting in undefined.
ConfigModule.forRoot({ isGlobal: true }) is true?Setting isGlobal: true makes ConfigModule available everywhere automatically, so you don't need to import it in every module to use ConfigService.