2

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...

wscourge
11.4k17 gold badges65 silver badges87 bronze badges
asked Jan 25, 2018 at 5:21
1
  • 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 believe Commented Feb 27, 2018 at 9:15

2 Answers 2

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'})

answered Jan 25, 2018 at 5:25
Sign up to request clarification or add additional context in comments.

7 Comments

console.log(__dirname) gives /.
Nope, Windows in Documents/projDirectory.
Yes I did, gave /.
Sorry, neither of those worked. With or without . in the env filename, checked that too.
@IronWaffleMan - This solution works, are you sure you are calling your process.env after you have required dotenv?
|
0

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.

answered Mar 25, 2020 at 20:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.