Configuring a Proxy in a React Project Using http-proxy-middleware

This article walks through setting up and debugging a CORS‑handling proxy in a React 18 project with create‑react‑app, using http‑proxy‑middleware to forward /api requests, configure logging, and verify the real request paths.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Configuring a Proxy in a React Project Using http-proxy-middleware

During recent React development I encountered a CORS issue that is usually solved on the backend; due to special circumstances I had to handle it on the frontend, so I documented the whole configuration process for future reference.

Environment

Project created with create-react-app; React v18.2.0

Using http-proxy-middleware v2.0.6

Operation Process

The prefix proxy is implemented with http-proxy-middleware v2.0.6.

1. Install the proxy plugin

npm install http-proxy-middleware --save

2. Configure the proxy and debug

(1) Add setupProxy.js file

Note: This file must be placed under the src directory.

(2) Proxy configuration

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
  app.use(
    createProxyMiddleware('/api', {
      target: 'http://192.168.3.11:5000',
      changeOrigin: true,
      // Remove the prefix so the backend receives a normal path
      pathRewrite: { '^/api': '/api' },
    }),
    // You can configure multiple proxies
    createProxyMiddleware('/2api', {
      target: 'http://192.168.3.11:6000',
      changeOrigin: true,
      pathRewrite: { '^/2api': '' },
    })
  );
};

(3) Interface debugging

Example using a project‑specific localAxiosInstance (a wrapper around axios).

import { localAxiosInstance } from '@/axios/localTestAxios';
export const testApiProxy = () => {
  return localAxiosInstance.get('/services/admin/SystemDic/GetPageSystemChannel', {
    params: { MaxResultCount: 10, SkipCount: 0 },
  });
};

The localAxiosInstance is created as follows:

let localAxiosInstance = axios.create({
  baseURL: LOCAL_TEST_URL, // constant value is '/api'
  timeout: 1000 * 60,
  /**
   * Indicates whether credentials (cookies) should be sent with cross‑origin requests.
   */
  withCredentials: true,
});

(4) Test whether the proxy works

Run the project and check if the API call succeeds.

(5) View the real request path after proxying

http-proxy-middleware

provides two useful options: logLevel: string, one of 'debug', 'info', 'warn', 'error', 'silent' onProxyReq: function, subscribes to the underlying

http-proxy
proxyReq

event.

Updated setupProxy.js with logging:

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
  app.use(
    createProxyMiddleware('/api', {
      target: 'http://192.168.3.11:5000',
      changeOrigin: true,
      pathRewrite: { '^/api': '/api' },
      logLevel: 'debug',
      onProxyReq: (proxyReq, req) => {
        console.log('[HPM] %s %s %s %s', req.method, req.originalUrl, '->', req.url);
      },
    }),
    createProxyMiddleware('/2api', {
      target: 'http://192.168.3.11:6000',
      changeOrigin: true,
      pathRewrite: { '^/2api': '' },
    })
  );
};

Note: After modifying the configuration, restart the development server. The console in VSCode will now display the logged proxy requests.

Conclusion

We have completed the proxy configuration for a React project, demonstrating that the process is straightforward once the steps are clear. This summary serves as a personal record and a reference for anyone facing similar CORS challenges.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptProxyReactCORShttp-proxy-middleware
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.