0

I would configure enivrement variables in nestjs as mentioned in documentation here:

in my service constructor I get env file path

import * as dotenv from 'dotenv';
import * as fs from 'fs';

export class ConfigService {
  private readonly envConfig: { [key: string]: string };

  constructor(filePath: string) {
    this.envConfig = dotenv.parse(fs.readFileSync(filePath))
    console.log(this.envConfig)
  }

  get(key: string): string {
    return this.envConfig[key];
  }
}

Then in config module I set the config service

  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(`${process.env.NODE_ENV}.env`),
    },
  ],
  exports: [ConfigService],
})

Current behavior

Actually I get process.env.NODE_ENV value undefined

Expected behavior

get env variable path in process.env.NODE_ENV

infodev
  • 4,673
  • 17
  • 65
  • 138
  • Provide `filePath` value what you want. Example it is `my_test.env`, then you have to set your `NODE_ENV` to `my_test`, we have too many way to set `NODE_ENV` environment variable value, a simple way `NODE_ENV=my_test npm run start` – hoangdv May 11 '19 at 16:31
  • Possible duplicate of [Defining Node environment in Nest.js](https://stackoverflow.com/questions/55092953/defining-node-environment-in-nest-js) – Kim Kern May 12 '19 at 07:38
  • Also see this answer https://stackoverflow.com/a/54364907/4694994 – Kim Kern May 12 '19 at 07:38

1 Answers1

2

I've faced the same issue. Easy fixed it by manually importing dotenv in file main.ts, just like in the example below (please make sure you've installed dotenv):

import { NestFactory } from '@nestjs/core';
import { config } from 'dotenv';
config();
// all rest of your code

Hope it might help!