0

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?

James
  • 35
  • 6
  • Does this answer your question? [Adding an .env file to React Project](https://stackoverflow.com/questions/49579028/adding-an-env-file-to-react-project) – Janez Kuhar Oct 19 '22 at 21:48

1 Answers1

1

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",
Colin Hale
  • 824
  • 5
  • 11
  • I just attempted that. Upon doing a console log, it responds with the following... GET http://localhost:3000/undefined/graph/tech-stack-by-role 404 (Not Found) – James Oct 19 '22 at 21:46