Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically change target via request headers #1631

Open
enchorb opened this issue Apr 5, 2023 · 3 comments
Open

Dynamically change target via request headers #1631

enchorb opened this issue Apr 5, 2023 · 3 comments

Comments

@enchorb
Copy link

enchorb commented Apr 5, 2023

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

chimurai/http-proxy-middleware#273

@Yrobot
Copy link

Yrobot commented Jun 24, 2023

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

@zenflow
Copy link

zenflow commented Jul 12, 2023

@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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants