dotenv file is not loading environment variables

Javascriptnode.jsDotenv

Javascript Problem Overview


I have .env file at root folder file

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

And server.js file in the root/app/config/server.js folder. The first line of server.js file is

require('dotenv').config();

I also tried following:

require('dotenv').config({path: '../.env'});

require('dotenv').config({path: '../../.env'});

However, my env variable are not loaded when I run the server.js file from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing. Any suggestion is highly appreciate. Thanks.

Javascript Solutions


Solution 1 - Javascript

How about use require('dotenv').config({path:__dirname+'/./../../.env'}) ?

Your problem seems to be the execution path.

Solution 2 - Javascript

This solved my issues in Node v8.14.1:

const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

Simply doing require('dotenv').config({path:__dirname+'/./../../.env'}) resulted in a location that resolved as /some/path/to/env/./../../.env

Solution 3 - Javascript

Here is a single-line solution:

require('dotenv').config({ path: require('find-config')('.env') })

This will recurse parent directories until it finds a .env file to use.

You can also alternatively use this module called ckey inspired from one-liner above.

.env file from main directory.

# dotenv sample content
USER[email protected]
PASSWORD=iampassword123
API_KEY=1234567890

some js file from sub-directory

const ck = require('ckey');
 
const userName = ck.USER;     // [email protected]
const password = ck.PASSWORD; // iampassword123
const apiKey   = ck.API_KEY;  // 1234567890

Solution 4 - Javascript

If you are invoking dotenv from a nested file, and your .env file is at the project root, the way you want to connect the dots is via the following:

require('dotenv').config({path:'relative/path/to/your/.env'})

Solution 5 - Javascript

I've had this problem and it turned out that REACT only loads variables prefixed with REACT_APP_

VueJs can have a similar issue as it expects variables to be prefixed with: VUE_APP_

Solution 6 - Javascript

One of the comments in @DavidP's answer notes logging the output of dotenv.config with

console.log(require("dotenv").config())

This will output a log of the config and display errors. In my case it indicated the config method was referencing the current directory instead of the parent directory which contained my .env file. I was able to reference that with the following

require('dotenv').config({path: '../.env'})

Solution 7 - Javascript

In the remote case that you arrive till this point, my issue was quite dumber: I wrongly named my env variables with colon ":" instead of equals "=". Rookie mistake but the resulting behavior was not loading the misspelled variables assignment.

# dotenv sample content

# correct assignment
USER[email protected]

# wrong assignment (will not load env var)
USER : [email protected]

Solution 8 - Javascript

Try this:

const dotenv = require('dotenv');
dotenv.config({ path: process.cwd() + '/config/config.env' });

worked for me idk how??

Solution 9 - Javascript

Be sure to load .env at the beginning of the entry file (e.g. index.js or server.js). Sometimes, the order of execution loads the environment variables after the services are initiated. And, by using __dirname, it can easily point to the file required relative to the current file.

Here my project structure is like this.

.
├─ src
│  └─ index.ts
└─ .env
// index.ts
import dotenv from 'dotenv';
import path from 'path';

dotenv.config({path: path.join(__dirname, '..', '.env')});

...

Solution 10 - Javascript

This solved the issue for me:

const path = require('path');
require('dotenv').config({
  path: path.resolve('config.env'),
});

Solution 11 - Javascript

You can first debug by using console.log(require('dotenv').config()). In my scenario, my .env file is in root directory and I need to use it in a nested directory. The result gives me { parsed: { DATABASE_URL: 'mongodb://localhost/vidly', PORT: '8080' } }. So I simply parse the result and store it in a variable const dotenv = require('dotenv').config().parsed;. Then access my DATABASE_URL like a JS object: dotenv.DATABASE_URL

Solution 12 - Javascript

It took me a few head scratches, and the tip to log the output of the require statement to console was really helpful. console.log(require('dotenv').config());

Turns out I was running my app from my user/ directory with nodemon application_name/. and that was making dotenv look for the .env file in my home dir instead of the app's. I was lazy by skipping one cd and that cost me a few minutes.

Solution 13 - Javascript

In my case .env was read fine, but not .env.local.

Updating package.json to name .env into .env.local ( cp ./.env.local .env) solved the problem:

  "myscript": "cp ./.env.local .env && node ./scripts/myscript.js"

Solution 14 - Javascript

One time I have got the same problem. Dotenv did not load .env file. I tried to fix this problem with a path config, to put .env file in a root folder, to put .env in the folder where the file is running and nothing helps me. Then I just trashed Node_modules folder, reinstall all dependencies and it works correctly

Solution 15 - Javascript

You can need the path of the .env file relative to the current working directory from where the application was launched. You can create this path like this:

const path = require('path')
require('dotenv').config({path: path.relative(process.cwd(), path.join(__dirname,'.env'))});

process.cwd() returns the absolute path of the working directory.
__dirname returns the absolute path of the application.
path.join() adds the path of the .env-file to the path of the application. so if your .env file is nested deeper, just add the folders (e.g. path.join(__dirname, 'config', 'secret','.env'))
path.relative() creates the relative path.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionANewGuyInTownView Question on Stackoverflow
Solution 1 - JavascriptYonghoon LeeView Answer on Stackoverflow
Solution 2 - JavascriptDavidPView Answer on Stackoverflow
Solution 3 - JavascriptJRosalView Answer on Stackoverflow
Solution 4 - Javascriptzero_coolView Answer on Stackoverflow
Solution 5 - JavascriptGreg Pagendam-TurnerView Answer on Stackoverflow
Solution 6 - JavascriptDigglitView Answer on Stackoverflow
Solution 7 - JavascriptdnhydeView Answer on Stackoverflow
Solution 8 - JavascriptAditya SinghView Answer on Stackoverflow
Solution 9 - JavascriptArkar Min TunView Answer on Stackoverflow
Solution 10 - JavascriptFranco FontanaView Answer on Stackoverflow
Solution 11 - JavascriptJason HuangView Answer on Stackoverflow
Solution 12 - Javascriptthiago-clubedochaveiroView Answer on Stackoverflow
Solution 13 - JavascriptegoView Answer on Stackoverflow
Solution 14 - JavascriptOleg PuzankinView Answer on Stackoverflow
Solution 15 - JavascriptjuppicView Answer on Stackoverflow