import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot()], }) export class AppModule {}
By default, ConfigModule.forRoot() loads environment variables from a .env file located in the project root directory. You don't need to specify the path unless you want to load a different file.
.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')); } }
The ConfigService.get() method returns the value as a string from the environment variables loaded. Since PORT=3000 is set, it returns the string "3000".
The correct option to specify a custom environment file path is envFilePath. Other keys like path, env_path, or envFile are invalid and cause errors.
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'); } }
If the .env file is missing or not in the root directory, ConfigModule won't load the variables, so configService.get('API_KEY') returns undefined.
Setting isGlobal: true makes the ConfigModule available across the entire app without needing to import it in every module manually.