Taylor Christie
Taylor Christie

Reputation: 356

How to proxy websocket connections to other websockets in NodeJS

I need to create a small authentication layer on top of a 3rd party web-socket based chat application. I have a simple API (get) that can validate api tokens from requests. What I want to do is essentially validate their token (which I know how to do) then proxy the websocket connection to the actual chat server.

I've been looking for solutions and this thread seems to give some pointers in the right direction however I can't get any of the solutions to work.

var http = require('http'),
    WebSocket = require('faye-websocket'),
    conf = require('./conf.json');

var server = http.createServer();

server.on('upgrade', function(request, socket, body) {
  console.log('upgrade fired');
  var frontend = new WebSocket(request, socket, body),
      backend  = new WebSocket.Client('ws://echo.websocket.org');

  frontend.pipe(backend).pipe(frontend);
});




server.on('connection', function(socket) {
  console.log('connection')
  backend = new WebSocket.Client('ws://echo.websocket.org');
  console.log(backend);
  socket.pipe(backend).pipe(socket);
})



server.listen(conf.port);
console.log('Listening on '+port.conf);

The connection event is fired, however the upgrade event which is supposed to be fired on a ws connection never is.

The goal is to first authenticate a api key to an external server, then open a proxy to the chat websocket all through a request to this node server via a websocket connection. I'll most likely pass the api key as a get parameter for simplicity. I also looked at this package and attempted using it however it didn't work as well.

Upvotes: 3

Views: 3704

Answers (1)

Taylor Christie
Taylor Christie

Reputation: 356

The issue ended up being with nginx. I forgot I was proxying requests through the reverse proxy and by default nginx does not support the ws:// connection so it drops it.

Upvotes: 3

Related Questions