Search code examples
javascriptnode.jscreate-react-apphttp-proxy

How do you setup an API proxy in the CRA dev server?


I am having issues developing a React app. When in development, my the app runs on localhost:3000 and my backend server (which hosts the /api endpoint) runs on localhost:80. The frontend makes calls to localhost:80/api but they fail because of the same origin policy (or missing CORS). I tried solving the issue by setting up a proxy in my package.json with the following line:

"proxy": "http://localhost:80"

The Create-React-App docs say that using a proxy "tells the development server to proxy any unknown requests to your API server..." Now for whatever reason, rather than proxying requests for /api to localhost:80, React is signaling a redirect (HTTP 301) to localhost:80. This is causing the CORS errors to still occur.

You can see from this screenshot of the network traffic that the front end is making a request for my /api endpoint and the backend is signaling to redirect: network traffic

The React docs specifically say that using a proxy "avoids CORS issues and error messages" in development, so I expect that I have the correct solution but I am setting it up the wrong way.

Is there a way I can prevent these CORS problems without using a Chrome extension?


Solution

  • Configuring the Proxy Manually

    Following create-react-app's documentation on configuring the proxy, you need to create the src/setupProxy.js file and export a function that adds a proxy middleware to the Express app. They recommend using http-proxy-middleware.

    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    module.exports = function(app) {
      app.use(
        '/api',
        createProxyMiddleware({
          target: 'http://localhost:5000',
          changeOrigin: true,
          followRedirects: true // This will likely fix the redirect issue
        })
      );
    };
    
    • It is recommended that you put all of your proxy logic into this file and remove the "proxy" field from your package.json.
    • You don't need to import this file anywhere.
    • This file only supports Node.js syntax/features.