I created .env
file in the root of my directory with data REACT_APP_API_URL=http:\\localhost:3001
, but when I run and get value from process.env
, I get an empty object, how can I fix that?
Asked
Active
Viewed 1,319 times
2

Philip Wrage
- 1,505
- 1
- 12
- 23

Nodir Nasirov
- 1,488
- 3
- 26
- 44
-
1The `REACT_APP_API_URL` needs to be changed to `http://localhost:3001` with forward slashes I think. Although that may not be the solution to the entire problem, I believe you would run into that problem at some point or the other! Currently, the URL uses backslashes which do not form a valid URL. – Anuj Khandelwal May 19 '19 at 05:03
-
I tries any types of strings, with and without slashes, no luck – Nodir Nasirov May 19 '19 at 05:08
-
Are you using Create react app or you have defined your own webpack configuration? – tarzen chugh May 19 '19 at 06:09
1 Answers
1
You need to integrate variable with start script.
"scripts": {
"start": "REACT_APP_API_URL=http://localhost:3001 react-scripts start", //like this
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
then you need to run your app. it will take all paramerters.
Or another way to run it pass it using command line. Ex: you need to pass env variable first before loading scripts
REACT_APP_API_URL=http://localhost:3001 npm start
You can also use package for better env management(cross-env) It will take care all env related management. Feel free to check there doc.
If you want to use cross-env you have to only do this for running enviornment from .env file(Note:.env file should be on package.json level)
"scripts": {
"start": "cross-env react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
it will load all your configuration from .env file whenever you want to use.

Shubham Verma
- 4,918
- 1
- 9
- 22