Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Having issues with fetching an environment variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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",
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading