Proxying websockets with single "proxyServer" to multiple targets

883 Views Asked by At

I am developing a nodeJS websocket proxy server. The use case is when a websocket request comes, I will check its credentials, add new headers and then based on its group (from user id) to redirect the websocket connection to its target webscoket server. I found most of the packages (such as node-http-proxy) supports single target. Is there a package supporting multiple targets ?

2

There are 2 best solutions below

1
On

From the README of node-http-proxy section, "Setup a stand-alone proxy server with custom server logic":

var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
});

Therefore, you should be able to add your decision code in the callback function and then make a proxy.web() call with your determined target.

0
On

Maybe it will help. What I did in that case

proxyServer.on('upgrade', function (req, socket, head) {
    const target = getTargetRoute(req)
    if (_.isNil(target)) {
      logger.error(`No target`)
      return
    }
    proxy.ws(req, socket, head, { target })
  })