React + node project, got my .env file in root (along with all other root files like .eslint, .gitignore), it contains 6 lines like APIKEY=aeofiunoief, no other special symbols.
In src/ I have index.js which does normal imports (like React, ReactDOM), then //eslint-disable import/first, then require('dotenv').load(). According to everything I've seen this should load my variables into process.env, but when I check console.log, I don't see anything but NODE_ENV and PUBLIC_URL.
It's really confusing...
-
The npm package dotenv should work straight out the box, the latest version of create-react-app I believe should also load your custom environment variables, there is a little trick though you have to prepend the variable with REACT_APP_ Only variables starting with REACT_APP_ are imported. Its a security thing I believeFaktor 10– Faktor 102018年02月27日 09:15:32 +00:00Commented Feb 27, 2018 at 9:15
2 Answers 2
Your file structure:
src
index.js
...
.env
...
Do:
require('dotenv').config({ path: '../.env' });
console.log(process.env);
From dotenv GitHub:
You can specify a custom path if your file containing environment variables is named or located differently.
require('dotenv').config({path: '/custom/path/to/your/env/vars'})
7 Comments
console.log(__dirname) gives /.Documents/projDirectory./.. in the env filename, checked that too.process.env after you have required dotenv?In my case, I was using the Dotenv webpack plugin and I was pointing to the wrong file path:
plugins: [
htmlWebpackPlugin,
new Dotenv({
path: path.resolve(__dirname, .., '.env')
})
],
For my structure, path: path.resolve(__dirname, '.env') was the right configuration that worked. As long as you are pointing to the right .env within your system, you should be good.