http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.88k stars 1.97k forks source link

Dynamically change target via request headers #1631

Open enchorb opened 1 year ago

enchorb commented 1 year ago

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

Yrobot commented 1 year ago

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

zenflow commented 1 year ago

@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 });
});
tbontb-iaq commented 1 month ago

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.