English 中文(简体)
NestJS ConfigModule not loading the correct .env file
原标题:
  • 时间:2022-07-26 09:44:53
  •  标签:
  • nestjs

I have 2 different file with environment variables: .env.development and .env.production.

I am trying to load the correct file through the ConfigModule like so:

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: `.env.${process.env.NODE_ENV}`,
      isGlobal: true,
    })
  ],
})

In package.json I specify the right NODE_ENV per startup script:

"start:dev": "NODE_ENV=development nest start --watch",
"start:prod": "NODE_ENV=production node dist/main",

My development file contains PORT=2994 and production contains PORT=2997.

In my main.ts file I am logging both the PORT and the .env. file path + NODE_ENV of the ConfigService, like so:

const port = configService.get<number>( PORT );
console.log( Running on port:  , port);
console.log(`.env.${configService.get( NODE_ENV )}`);

The NODE_ENV file path log is always correct (.env.development for development and .env.production for production). The port however, which is supposed to be retrieved from the correct file is logged 2994 on both development and production.

Only when I remove or empty the .env.development file, the production values are used. It seems as if the .env.development will always take precedence over the .env.production file.

What am I doing wrong here?

问题回答

I had the same issue, and I solved it just adding .trim() after process.env.NODE_ENV. Please let me know if it helps, this is a part of ConfigModule:

ConfigModule.forRoot({ envFilePath: [${process.env.NODE_ENV.trim()}.env], }),





相关问题
how to have http response with pipe throwing error?

I have a nestjs application in which I created a pipe to check if value is a valid URL. If the URL is invalid, throw error. This is used in a controller to save an item into the database. I just ...

Can t set cookie in response NestJs

I Have a nestjs graphQL auth microservice and trying to set a http only cookie containing the token, and for some reason setting the cookie doesn t work, i get this error: { "errors": [ ...

store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

NestJS ConfigModule not loading the correct .env file

I have 2 different file with environment variables: .env.development and .env.production. I am trying to load the correct file through the ConfigModule like so: app.module.ts @Module({ imports: [ ...

热门标签