Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best location to store the API Root Url in React JS?

I'm using mern stack in a project I'm working on.

Currently I'm making requests to the rest api like so.

const { data } = await axios.get('http://localhost:5000/api/testimonials/');

The API is available at http://localhost:5000/

but when I will deploy this app that url will change.

With the current approach I have replace http://localhost:5000/ with the live url.

Instead of doing that I want to store the root url in a variable.

What is the best location to store the API root in React JS?

So I can use it in every request I make and when I have to update the url I just have to update that variable.

like image 669
Xaarth Avatar asked Nov 14 '25 14:11

Xaarth


1 Answers

You can do two things ,

  1. storing them in env variables by creating .env file for each environment

    CRA - .env

    Don't forget to prefix your names with REACT_APP_ , else it won't work

  2. using proxy in package.json .(This is the preferred way of using api in docs)

    It avoids cors error as mentioned in docs

    CRA - proxy

like image 121
timbersaw Avatar answered Nov 17 '25 08:11

timbersaw