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'));
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.
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.
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.
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.
Several scenarios:
.env
file.env
is incorrectly defined.env
located outside the server's root pathdotenv
packagefunctions
(or other deployable folder) the .env
is missing (even though it's in the root location it has to be there too)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With