Reputation: 23
in the .env file I set some variables //file .env
NAME="Darwin"
But when you call it in a js file, I get an undefined value //file index.js
console.log(process.env.NAME)
and when executing node index.js
undefined
Can you explain me why this happens, Thanks.
Upvotes: 2
Views: 2936
Reputation: 171
Import dotenv npm module.
const dotenv = require('dotenv').config();
console.log(process.env.NAME)
Upvotes: 0
Reputation: 769
When you create .env
file, for that time it is just a file like other js or text files, to use it we need to use dotenv
npm package.
Ref:
https://www.npmjs.com/package/dotenv
We need to use it on the top of our initial node project file.
i.e
index.js
Syntax For ES6/Type Script (With babel transpilation)
import dotenv from 'dotenv';
dotenv.config();
or
dotenv.config({path: `<path of .evn file>`});
Syntax for ES5 node js environment
require('dotenv').config();
or
require('dotenv').config({path: <path of .env file>});
By default it is taking .env from the project working directory, but if you have created the .env file with different name than you need to specify the path.
After that you can console your env variable inside the code anywhere.
Upvotes: 0
Reputation: 1163
If you include the dotenv dependancy you won't have this problem https://www.npmjs.com/package/dotenv
Then simply add at the top of your script
import dotenv from 'dotenv';
dotenv.config();
(if you have es6 via babel / createreactapp etc)
or
require('dotenv').config();
Upvotes: 3