node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

Dynamically change target via request headers

Open enchorb opened this issue 2 years ago • 3 comments
trafficstars

Switched to Vite which uses this library under the hood. Any way to switch the target based on request headers like the below library,

https://github.com/chimurai/http-proxy-middleware/issues/273

enchorb avatar Apr 05 '23 22:04 enchorb

same question. no idea on how to change the path for proxy, after reading the README.

Yrobot avatar Jun 24 '23 16:06 Yrobot

@enchorb @Yrobot I think your question is for Vite, not this library

The first section of this library's README implicitly shows how you can do that if you're using the library directly

var proxy = httpProxy.createProxyServer(options);

http.createServer(function(req, res) {
  var target = req.headers.whatever === 'bar' ? 'http://mytarget1.com:8080' : 'http://mytarget2.com:8080'
  proxy.web(req, res, { target: target });
});

zenflow avatar Jul 12 '23 05:07 zenflow

In Vite, you can change target via request like this:

server: {
  proxy: {
    '/__vite_dev_proxy__': {
      changeOrigin: true,
      configure(_, options) {
        options.rewrite = path => {
          const proxyUrl = new URL(path, 'file:'),
            url = new URL(proxyUrl.searchParams.get('url'))

          options.target = url.origin
          return url.pathname + url.search
        }
      },
    },
  },
}

And request with http://localhost:5173/__vite_dev_proxy__?url=https://example.com.

If you want to change target based on request header, you can listen to the start or proxyReq events, get the request headers in the handler, and modify target.

tbontb-iaq avatar Jul 18 '24 15:07 tbontb-iaq