How to Setup Proxy in React with http-proxy-middleware

How to Setup Proxy in React with http-proxy-middleware

A simple way to fix invalid options object error when using a proxy to your backend

ยท

2 min read

Sometimes, trying to communicate with your backend can be a hassle, and one of the errors that are most common when I set up a proxy in react is this

"Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. [1] - options.allowedHosts[0] should be a non-empty string."

In this article, we'll look at a simple way to solve this proxy issue using http-proxy-middleware to set up a new proxy from our React app.

Requirements

  • Basic knowledge of React & Node

  • react-scripts@0.2.3 or higher

Steps to set up Proxy in React

Step 1: Create your react app and install http-proxy-middleware via npm:

npx create-react-app 'your-app-name'
npm install http-proxy-middleware

Step 2: Create a setupProxy.js file in the client (React) src folder and copy this code:

IMPORTANT: Be sure to name the file setupProxy in your src folder as it's recommended for it to be recognized by React.

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

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

No need to import any file anywhere, it's registered once you start the server.

Step 3: Consume the API wherever in your app and run your backend and FE

I'll be using the API with react-admin as an example.

Screenshot of API consumption

What you need to do is just reference your backend URL to it, which in my case is running at localhost:5000 and you're good to go!

Congratulations ๐ŸŽ‰๐ŸŽ‰

Now, you know how to set up a proxy in React using http-proxy-middleware! ๐Ÿฅณ This was one of my shorter articles, but I do hope you find this useful if you come across a similar error. Thank you for reading and I hope you have a nice day ahead! ๐Ÿ˜„

References

Let's Connect!

ย