Why You Should Use React DevServer Proxy

Learn how and why you need to set up the React DevServer Proxy

Manusha Chethiyawardhana
Bits and Pieces

--

Why you should use React DevServer Proxy

Today, any frontend library like React comes with a DevServer where we run it in localhost using a different port than the backend API.

However, it also brings in a unique set of challenges that we need to address at development time.

This article will explain these challenges and ways to overcome them by using a DevServer Proxy.

Why Do You Need To Use A DevServer Proxy?

There are multiple reasons to use a Proxy Server for development. Let’s look at them one by one.

1. No more CORS errors and need for preflight requests

CORS (Cross-Origin Resource Sharing) error is one of the most annoying things you encounter when developing and testing web applications.

CORS error happens when web browsers enforce the Same-Origin Policy to protect users from Cross-Site Scripting (XSS) attacks and other types of attacks.

This might not be an issue in production since both the frontend and the backend API are typically served from the same origin.

But, in development, you need to add a rule to your Backend CORS policies explicitly allowing the frontend DevServer origin. However, you can skip that by using a DevServer proxy by showing your browser that the backend API is also from the exact origin.

2. Easy handling of HTTP/HTTPS forwarding

The http-proxy-middleware gives the option of forwarding HTTP or HTTPS URLs to a specific path using ProxyTable. The below implementation shows how a ProxyTable can be used to redirect requests to a different target.

For example, requests can be routed using the host HTTP/HTTPS header or the request path.

const proxyTable = {
'integration.localhost:3000': 'http://localhost:8001',
'staging.localhost:3000': 'http://localhost:8002',
'/rest': 'http://localhost:8003',
};
const options = {
target: 'http://localhost:8000',
router: proxyTable,
};
const myProxy = createProxyMiddleware(options);

For example, if you want to plugin your frontend to a remote backend running on HTTPS, you can do that via the Proxy without causing any HTTPS resource access issues.

3. Easy to simulate the production environment

The DevServer Proxy makes it easier to test applications in development before they go live.

For example, assume you have a path change in an API URL and test it before deploying to production. This can be easily accomplished by using the pathRewrite option in http-proxy-middleware.

pathRewrite: {
'^/api/old-path': '/api/new-path',
},

4. Easy to control error logging

When it comes to determining the source of errors, logging is extremely helpful. Since http-proxy-middleware has different log levels defined, we can use it to control the amount of logging.

The logLevel : 'debug' will show you all the logs.

You can also use the Log Provider attribute in http-proxy-middleware to configure your own logger.

5. Simple to work with relative paths in frontend

You can bring the development environment much closer to production. For instance, your frontend can work with the relative URL of the backend API both in development and production.

The DevServer Proxy will take care of the absolute paths in the development environment. This saves frontend developers time because they no longer need to configure the host part of the URL.

So, let’s look at how we can configure the DevServer Proxy with React.

Setting up the DevServer Proxy in Practice

There are two main ways to set up DevServer Proxy for a React frontend. You can choose either one based on what you expect from the proxy.

1. Proxy Setup with Create-React-App

Setting up the DevServer Proxy for your React project is a breeze with Create React App. This comes pre-configured with the webpack, saving you time.

All you have to do is add a proxy field to your package.json file, like shown below.

"proxy": "http://localhost:3000",

This line instructs the development server to proxy any unknown requests to your API server in development mode.

For example, when you use fetch(‘/api/test’), the development server will recognize that it is not a static asset and proxy your request to http://localhost:3000/api/test as a fallback.

2. Proxy Setup in Manual Mode

You can also manually set up the proxy using the open-source npm library called http-proxy-middleware. This library is compatible with many servers, including express and connect, and can be installed with the command below.

npm install http-proxy-middleware --save

After installing, create a file assetupProxy.js in the src folder of your React project and register the proxy as shown below.

const { createProxyMiddleware } = require('http-proxy-middleware');module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
})
);
};

This file automatically gets registered when you start the development server, so you don’t have to import this file anywhere else.

You can also proxy multiple APIs by modifying the above code.

app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3000',
changeOrigin: true,
})
);
app.use(
'/api2',
createProxyMiddleware({
target: 'http://localhost:3001',
changeOrigin: true,
})
);

Note: Even for a TypeScript project; this file should be in JavaScript.

Build better Component Libs and Design Systems

Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.

OSS Tools like Bit offer a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Conclusion

DevServer Proxy is a handy feature for every React Developer to use. It can accelerate the frontend development process and deliver many other value additions as well.

I hope you will give it a try in your next React project.

Thank you for reading, and happy coding!

--

--