How to Set Up a Proxy Server in React | Dealing with CORS
Tags: javascript, react, security, programming
Published: 2023-01-26 14:03:40

If you've built a web app that requires data from a different domain, you're likely familiar with the browser's same-origin policy and CORS. In this article, we'll explore how to bypass CORS issues using the proxying capabilities in React Boilerplate.

{% embed https://www.youtube.com/embed/KBPCoGsQ920 %}

CORS stands for Cross-Origin Resource Sharing, and it's a security mechanism that prevents browsers from loading resources from domains other than the one they're currently on. This helps keep malicious code out of web applications, but sometimes legitimate requests get blocked too!

Fortunately, [http-proxy-middleware](https://www.npmjs.com/package/http-proxy-middleware) library comes with an easy solution: proxying.

A proxy is basically a go-between between your domain and another one. With http-proxy-middleware library, you can set up a reverse proxy by adding a configuration in your project. In this configuration, specify the hostname or IP address where the external resource will be requested from, as well as any specific headers that should be sent with each request. For example, if you're trying to get data from an API that requires authentication, you can specify the authorization header in your proxy configuration. Once this configuration is saved, React Boilerplate will automatically send requests through the configured proxy instead of directly to the remote server, bypassing CORS issues!

This kind of proxying is especially useful for testing and debugging applications where cross-domain data is required. With React Boilerplate's easy setup, you can quickly and safely access data from any source. So don't let those pesky CORS errors stop you - try using this solution today!

---

## CORS Error:
`Access to fetch at 'https://api.binance.com/api/v3/ticker/24hr' from origin 'http://localhost:3000' 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.
`

---

## How to set up a proxy server in React?

Note: In this example, we will utilize the widely-used react-boilerplate found at https://github.com/react-boilerplate/react-boilerplate as our starting point.

---

First, install the http-proxy-middleware library by running this command in your project's root directory.

```
npm install http-proxy-middleware
```

---

Next, create a new file in your project's [middlewares directory](https://github.com/codeofrelevancy/react-boilerplate-cors/tree/main/server/middlewares) called addProxyMiddleware.js. In this file, import the http-proxy-middleware library and use it to create a new proxy object that will handle the CORS issue.

```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function addProxyMiddleware(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://api.binance.com',
      changeOrigin: true,
    }),
  );
};
```

---

If needed, add the necessary CORS headers to the request. For example:

```javascript
headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
        'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
```

---

Now, use the addProxyMiddleware function in [frontendMiddleware.js](https://github.com/codeofrelevancy/react-boilerplate-cors/blob/main/server/middlewares/frontendMiddleware.js) to intercept all requests to your backend API.

```javascript
const addProxyMiddleware = require('./addProxyMiddleware');
addProxyMiddleware(app);
```

---

Lastly, in your React components or [saga.js](https://github.com/codeofrelevancy/react-boilerplate-cors/blob/main/app/containers/HomePage/saga.js), make API requests to `/api/v3/ticker/24hr` instead of `https://api.binance.com/api/v3/ticker/24hr`


```javascript
const requestURL = `/api/v3/ticker/24hrs?${serialize(params)}`;
```

---

## Full source code:
[react-boilerplate-cors](https://github.com/codeofrelevancy/react-boilerplate-cors)

---

## What is React Boilerplate?

> A highly scalable, offline-first foundation with the best developer experience and a focus on performance and best practices.

> React Boilerplate is a starter kit or template for building web applications using React.js. It typically includes a basic file and folder structure, as well as a set of common libraries and tools that are often used in React projects, such as webpack, babel, and eslint. React Boilerplate can help developers quickly set up a new project with a functional development environment, allowing them to focus on building the specific features of their app rather than spending time on the initial setup.

---

## What is http-proxy-middleware?

> The one-liner node.js http-proxy middleware for connect, express, next.js and more.

---

## What is a proxy server?

> A proxy server acts as an intermediary between a client and a server. It receives requests from clients, forwarding them to the appropriate server and returns the server's response to the client. This allows the proxy server to cache frequently requested resources and provide improved performance, security, and anonymity for the client.

> Additionally, a proxy server can be used to block access to certain websites or to filter network traffic based on certain criteria.

---

## Why you should use a proxy server in development?

> Using a proxy server in development can be beneficial for several reasons:

> **Access to blocked resources:** In some cases, certain resources or websites may be blocked by the developer's network. A proxy server can be used to bypass these restrictions and access the needed resources.

> **Security:** A proxy server can be configured to add an extra layer of security by filtering out potentially harmful requests or traffic.

> **Anonymity:** Developers can use a proxy server to hide their IP address and remain anonymous while testing their applications.

> **Improved performance:** A proxy server can cache frequently requested resources, which can lead to faster load times for the developer's application.

> **Ability to test different network configurations:** A proxy server can be used to simulate different network conditions, such as low bandwidth or high latency, to test how the developer's application behaves in these scenarios.

> **Remote development:** Developers can use a proxy server to access resources that are only available on the company's internal network remotely.

---

🍀Conclusion:

Please consider supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!


[YouTube](https://youtube.com/@codeofrelevancy)
[Discord](https://discord.com/invite/f8jwnzcRz2)
[GitHub](https://github.com/codeofrelevancy)