Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different API url for development and production with React and axios

I'm building web app with React frontend and Node.js backend (API).
In React frontend I call API methods like this:

axios({
    method: 'post',
    url: 'http://servername:9999/reports.activities',
    data: {
        user_id: 1
    }
}).then(res => {
    this.setState(res.data);
});

Sometimes I need to test API methods that is not released to production yet.
When I test backend locally, i run nodemon api.js on localhost:9999.
Every time I want to test frontend with local-running API, I have to change http://servername:9999 to http://localhost:9999 in my frontend code.
I think this is not the right approach.
What is the best way to use different url for development (when run npm start locally) and production (npm build)?
I was thinking of using dotenv for this purpose. Is this the right approach?
What is the best practice?

like image 490
Yura Avatar asked Oct 19 '18 16:10

Yura


People also ask

How do you integrate API with Axios in React?

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.

Where does API Store URL in React?

To store the API keys, create a new file called . env in the root directory of the React application. You can now access the API key in any file in the React app using process. env.


2 Answers

If you are using create-react-app you have already dotenv installed.

https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

So you can so:

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT || 'http://production';

...
url: `${API_ENDPOINT}/reports.activities`
like image 104
keul Avatar answered Oct 28 '22 09:10

keul


You can create 2 .env files called .env.development and .env.production.

//.env.development
REACT_APP_API_ENDPOINT=http://localhost:9999
//.env.production
REACT_APP_API_ENDPOINT=https://servername:9999

Then use it as follows -

//api.js
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT

axios({
    method: 'post',
    url: `${API_ENDPOINT}/reports.activities`,
    data: {
        user_id: 1
    }
}).then(res => {
    this.setState(res.data);
});

The way it works is: when you run npm start, react will use the .env.development file and when you do npm run build, react will use the .env.production file.

Here's the relevant part of the documentation.

like image 6
theairbend3r Avatar answered Oct 28 '22 09:10

theairbend3r