Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
user3775998 Avatar asked Nov 17 '14 13:11

user3775998


People also ask

How do I create an .env file?

In the explorer panel, click on the New File button as shown in the following screenshot: Then simply type in the new file name . env ...

What is .env file in Nodejs?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables. The dotenv library reads this.


2 Answers

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.

like image 67
Basheer AL-MOMANI Avatar answered Oct 15 '22 23:10

Basheer AL-MOMANI


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.

like image 44
teliz Avatar answered Oct 15 '22 22:10

teliz