node-http-proxy
node-http-proxy copied to clipboard
Dynamically change target via request headers
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
same question. no idea on how to change the path for proxy, after reading the README.
@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 });
});
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.