The useful setting of proxy for React


This post is written 26 months ago. Probably the information might be out of date.

When you want to request the API server during the local development

In the case of SPA, we need to throw API request to a server. Without any settings of cors, we can’t seccess to send requests to the API server because of SameOrigin policy.

For example, if you run your React app and API server locally with the following URL, it will be trapped by the browser’s SameOrigin policy because the port portion is different.

  • localhost:3000 for React
  • localhost:8080 for API server

For this case, in order to throw requests, we can enable cors on the backend side or we can add proxy property to package.json of React project. (The case of the React project created by npx create-react-app)

src/setupProxy.js
 "proxy": "http://localhost:8080",
copied!

Or we can add src/setupProxy.js. In this case, we can add several proxies.

src/setupProxy.js
const proxy = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(proxy("/api", { target: "http://localhost:8080/" }));
};
copied!

Note that the proxy setting is only effective during npm start, not after npm run build.

Reference

Proxying API Requests in Development

buy me a coffee