Overview of Proxy Servers and how we use them in React

Common Use Cases

In the below examples, we will examine the different ways of proxying our requests within a react application.

1. Using fetch

With a new application created using the create-react-app CLI we can jump straight into coding:

Without Proxy, the request is going to be rejected by google.com server and we see the rejection logged on the console.

But, when we add the proxy entry to our package.json the request is successfully proxied and we can load the information returned by the server. In this case, it is a blob so we need a bit of extra processing to extract the text.

Updated component:

and the result is logged to the UI as follows:

2. Using custom targets for different paths

Since not all requests go to the same server, we can define paths and target for each path in our package.json file:

In our component, while making requests, this configuration is applied and our requests are sent to the corresponding servers:

The response is out of order because of the async nature of the blob and .json() method as seen below:

One peculiar thing to notice is that we used the changeOrigin flag in our package.json file. This flag changes the origin of the host header to the target URL thus enabling successful connection. There are other similar and helpful options available here.

3. Using axios

If your application uses axios instead of fetch for making http requests, setting up proxy is still no different than what we have done so far.

Let us add another path to get the posts from typicode using axios. Install axios using npm or yarn before proceeding to update the package.json file as shown below:

The component can now be updated to make request with axios:

The advantage of using axios is that we can now add additional options and features to our http requests with ease. One such feature is the use of interceptors to intercept requests and responses per application rather than per request.

read original article here