Search code examples
node.jscreate-react-apphttp-proxy-middleware

How to rewrite request path using http-proxy-middleware in a react app?


I am using http-proxy-middleware in my react app, where I have a setup like this:

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

module.exports = function(app) {
  app.use(
    "/api/v1",
    createProxyMiddleware({
      target: "https:test.com/",
      changeOrigin: true
    })
  );
};

Some api requests of my applications has request url as: http://localhost:3000/products-and-details/api/v1/proxy/trend/api/v1/listProducts which I want to change it to: http://localhost:3000/api/v1/proxy/trend/api/v1/listProducts.

To achieve this I am modifying request paths before requests are send to the target using pathRewrite as below:

pathRewrite: {
        '^/products-and-details': ''
      }

However this doesn't seem to work and the request url remains the same with no changes. Can anyone please help to point out what am I doing wrong here?

Edit: My http-proxy-middleware dependency has a version ^2.0.3


Solution

  • My senior colleague helped me to fix this. It seemed that the request, http://localhost:3000/products-and-details/api/v1/proxy/trend/api/v1/listProducts was not at all intercepted by the proxy. Hence, to intercept those requests we have to make sure to include it in the context for our proxy middleware.

    So, in my case it was as described below:

    app.use(["/api/v1", "/products-and-details/api/v1"])
    

    And then use PathRewrite to modify request paths before the actual request is made to server as depicted below:

    pathRewrite: {"/products-and-details": ""}