Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS env variable undefined

I'm trying to set configuration variables on my project using the official documentation.

I added the following line to my app.module.ts imports:

ConfigModule.forRoot({
  isGlobal: true
}),

I created a .env file at the root of my project with the following content:

MY_VARIABLE=myself

And I use dependecy injection to get access to the configuration service:

constructor(private configService: ConfigService) {}

However the following line logs 'Env variable: undefined'

console.log('Env variable: ', this.configService.get<any>('MY_VARIABLE'));
like image 672
Platus Avatar asked Apr 26 '20 09:04

Platus


People also ask

How to use environment variables in nestjs?

By default, NestJS will look for a .env file inside the project root directory. If the file is present, it will merge the key/value pairs present in the .env file with other environment variables from the process.env. See below example of .env file. Basically, this is where we place our environment variables as key/value pairs.

How does dotenv work with @nestjs config?

The @nestjs/config package uses dotenv behind the scenes. In other words, the rules applicable to dotenv apply to @nestjs/config as well. In case a key exists in the runtime environment (via OS shell exports) and also in a .env file, the runtime value takes precedence. By default, the @nestjs/config looks for the .env file in the root directory.

What is nestjs config and how to use it?

Similar to custom configuration files, NestJS Config also supports namespaced configuration object. This allows us to separate configuration scopes such as database configuration, redis configuration and so on. Inside the registerAs () factory function, we can directly access the process.env object.

What to do if node_ENV is not set?

First, if NODE_ENV is not set, we try to get the absolute path of the development.env file, if this file does not exist, it will return the absolute path to the .env file. Let’s continue with adding some life to our environment files. You can see the file path below each code snippet.


1 Answers

Several scenarios:

  • You don't have .env file
  • .env is incorrectly defined
  • You're trying to access environmental variables from .env located outside the server's root path
  • You need to install dotenv package
  • Deploying to Serverless and in the functions (or other deployable folder) the .env is missing (even though it's in the root location it has to be there too)
like image 60
Daniel Danielecki Avatar answered Oct 07 '22 02:10

Daniel Danielecki