Many solutions exist to serve remote content on proxies : webpack-dev-server, next.js, http-proxy, or just my own local-traffic.
While these solutions offer an efficient way to route http traffic, they sometimes have support for websocket, which correspond to a different protocol (tcp messages but not exactly http)
The client only sends a http request once, then the client and server exchange messages without handshake (the initial message to initiate a connection).
Node.js does offer a way to intercept these messages, but only via the EventEmitter interface.
So you won’t be able to “listen” for websocket messages in a server.
I have written a wrapper to allow a server to intercept websocket messages and to forward them to a real websocket server. Using this tool, I am able to build a proxy server that is also able to proxy websockets.
This will be very useful to proxy hot reload functionalities on server and thus to keep a nice level of interactivity even behind the proxy server.
It is quite straightforward to explain the “upgrade” event callback :
When we get a request of type “upgrade”, we forward the request to the target, and we reply to the client once we get a response (which should be of status code 101).
We keep a reference to the upstream socket and the downstream socket, and we make sure to forward any message coming upstream or downstream to mirror the traffic transparently.
The upgrade callback should only be called once, and all the subsequent messages are supposed to be intercepted in either downstreamSocket on data, or in upstreamSocket on data.
To see a working example, just run local-traffic >= 0.0.39 with node.js