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.
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 ...
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.
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:
The filename should be .env
(I believe .env.test
is also acceptable).
Make sure you are requiring it as early as possible in your application using this statement require('dotenv').config();
The .env
file should be in the root directory of your project.
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.
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
.
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