In the root of my React project, I have this .env file containing the following.
DS_API_URL=[http://url.com](http:url.com/)
In another file of the project, an axios call utilizes this to return some stuff.
const url = 'http://url.com/graph/tech-stack-by-role'
will return what I need.
const url = `${DS_API_URL}/graph/tech-stack-by-role`;
returns an error.
How do I fetch the link from the env file and assign it to a var?
CodePudding user response:
To use environment variable in react you need to prefix the variable name with process.env.REACT_APP_. Documentation
So in your .env file you have:
REACT_APP_DS_API_URL=[http://url.com](http:url.com/)
Then to use:
const url = `${process.env.REACT_APP_DS_API_URL}/graph/tech-stack-by-role`
Update to answer question: update your start script to use the .env file you want. in this case it is .env.localhost. You will also need to npm install or yarn install env-cmd:
"start": "env-cmd -f ./.env.localhost react-scripts start",