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:
On some operating sytems (mostly some linux distros, I am looking at you raspbian), .env files don't work. rename them and import that
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
.
Take care that you also execute your Node script from the ROOT folder.
E.g. I was using a testing script in a subfolder called ./bin/test.js
.
Calling it like: node ./bin/test.js
worked totally fine.
Calling it from the subfolder like:
$ pwd
./bin
$ node ./test.js
causes dotenv
to not find my ./.env
file.
The '.env' file should be in the root directory of your node js server file (server.js or for me).
If you placed the '.env' file at the root of your project, it won't work. My mistake was that I have the server.js file nested in a folder named 'controller'.
So I had to fix it by placing the .env file in the same directory as the server.js file.
Working Solution:
If you are using webpack (which you definitely should), use a very handy plugin dotenv-webpack which solves the issue of reading environment variables from .env
file
Make sure
.env
is in root directory of your project.
Steps to install the plugin:
npm i -D dotenv-webpack
webpack.config
file: const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv(),
...
],
...
};
Now you can call any environment variable defined in .env
file using process.env
in any js
file
I had to literally use no name for the .env file, just have the .env extension and save the file like that and it worked.