How do I setup the dotenv file in Node.js?

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:

'use strict';
    
var dotenv = require('dotenv');
dotenv.load();
console.log('config');

I have another file .env at the root of my application folder. I also have an environment variable TWILIO_ACCOUNT_SID.

This is the process I go through while trying to use the environment variables in a certain function:

$ node
> require('./config/config.js');
config
{}
> process.env.TWILIO_ACCOUNT_SID
undefined

I defined the TWILIO_ACCOUNT_SID in my .env file but as soon as I try to output the value in my console, I get an error stating that the variable is undefined.

I will be very grateful for any support in troubleshooting this issue.


Solution 1:

In my case, every time I tried to get a key from the .env file using process.env.MY_KEY, it returned undefined.

I suffered from this problem for two hours just because I named the file something like keys.env which is not considered to be a .env file.

So here is the troubleshooting list:

  1. The filename should be .env (I believe .env.test is also acceptable).

  2. Make sure you are requiring it as early as possible in your application using this statement require('dotenv').config();

  3. The .env file should be in the root directory of your project.

  4. Follow the "file writing rules" like DB_HOST=localhost, no need to wrap values in double/single quotes.

Also, check the documentation of the package on the NPM site.

Solution 2:

I solved this using:

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

or with an absolute path:

C:\\asd\\auhsd\\.env

If it does not find the .env file, it will return undefined.

Solution 3:

Save yourself some troubleshooting time and log your require call, like so:

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

You should see an error with more detailed info on the problem.