How to set up a proxy for multiple APIs in React

Today we will show you how to set up a proxy for multiple APIs in React.

In the previous article, we explained how to set up a proxy for a single API in the react application. There we have set the proxy attribute in package.json.

Set up a proxy for multiple APIs in React

  1. Create a react application
  2. Install npm dependency
  3. Configure a proxy for multiple APIs
  4. Output

1. Create a react application

Let’s create a react application using the create-react-app. Run the following command to create a new application.

2. Install npm dependency

Here, we will use the http-proxy-middleware npm package to configure proxy middleware in react application. Run the following command to install proxy middleware in the application.

3. Configure a proxy for multiple APIs

Let’s configure a proxy using http-proxy-middleware.

Step 1: Create a setupProxy.js file in the src directory and write the following code in the file.

In the above code, we have set the two different API endpoints in the target attributes.

Step 2: Let’s call an API via a new path (/api1 & /api2) and capture output in the console logs.

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

That’s all you have to do.

4. Output

Now, run the react application and check the output in the browser console. Your CORS error will be gone.

Output - Proxy for multiple APIs - Clue Mediator
Output – Proxy for multiple APIs – 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...

Leave a Reply

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