How to set up a proxy in React App

In this article, we will show you how to set up a proxy in React Application. Most of the beginners are facing the CORS issue while they are working with REST API integration in react application.

You may encounter the following CORS error.

CORS error

Access to fetch at ‘<BACK_END_URL>’ from origin ‘<FRONT_END_URL>’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Solutions

There are two ways to fix this issue.

  1. Enable the CORS at server side (How to enable CORS in Node.js)
  2. Configure proxy in react app

Here, we will see how to set up a proxy in the react app.

Set up a proxy in React App

  1. Call an API from the create-react-app
  2. Configure a proxy to resolve the CORS error
  3. Output

Check the following article to configure multiple proxy.

How to set up a proxy for multiple APIs in React

1. Call an API from the create-react-app

In the first step, we will create a react app using the create-react-app and call the REST API to get the API response.

App.js

In the above code, we have used the https://3c872b93c048.ngrok.io endpoint to call an API using the fetch. You can use the other packages to call an API such as Axios.

Recommended: POST request using axios with React Hooks

You will get the following CORS error on page load.

CORS Error - Clue Mediator
CORS Error – Clue Mediator

Let’s set up the proxy to fix the CORS error.

2. Configure a proxy to resolve the CORS error

Follow the 3 steps to configure the proxy in react app.

Step 1: Set the proxy attribute in the package.json. It should be ”proxy”: “<BACK_END_URL>”. Assign only the endpoint of the API as a proxy.

package.json

Step 2: Restart the react application by running the npm start command.

Step 3: Remove the API endpoint from the component code and use the pure routes.

App.js

That’s all you have to do.

3. Output

Now, run the react application and check the output in the browser console.

API Response - Clue Mediator
API Response – Clue Mediator

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. Pascal says:

    If I understand correctly, this method only works for development.
    How would you avoid the CORS message for a production build? Or will this method also work for that?

Leave a Reply

Your email address will not be published. Required fields are marked *