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`.
Checkout more articles on ReactJS
- How to add a loading in React AG Grid
- Barcode scanner in React
- Get the country flag from the country code in React
- Test an input field using the React Testing Library
- Loading data asynchronously and download CSV using react-csv
Set up a proxy for multiple APIs in React
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.
npx create-react-app multiple-proxies-react-app
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.
npm i http-proxy-middleware
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.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware('/api1', {
target: 'https://b87baeb75efe.ngrok.io', // API endpoint 1
changeOrigin: true,
pathRewrite: {
"^/api1": "",
},
headers: {
Connection: "keep-alive"
}
})
);
app.use(
createProxyMiddleware('/api2', {
target: 'https://c43694c322b8.ngrok.io', // API endpoint 2
changeOrigin: true,
pathRewrite: {
"^/api2": "",
},
headers: {
Connection: "keep-alive"
}
})
);
}
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.
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
fetch('/api1/products')
.then(res => res.json())
.then(res => {
console.log('Output 1:', res);
});
fetch('/api2/products')
.then(res => res.json())
.then(res => {
console.log('Output 2:', res);
});
}, []);
return (
<div>
<h3>Set up a proxy for multiple APIs in React - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></h3>
<p>Open Console to check the logs.</p>
</div>
);
}
export default App;
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
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂