Can I chain WebSocket middlewares up?
In Express' philosophy, things are handled part by part in different middlewares. Can I partially handle a WebSocket connection in one middleware and leave it to another, or are there any work-around to achieve the same goal? For example,
app.ws('/', function(ws, req, next) {
ws.on("message", function(msg) {
// do something
next(); // call `next` here
});
});
app.ws('/', function(ws, req) {
ws.on("message", function(msg) {
// do something else
});
});
To be specify, I want to share the same user authentication mechanism with both HTTP and WebSocket, so I need to forward Cookies using WebSocket. Then, I need a middleware to place the forwarded Cookies back into the req parameter. Is it possible?
Currently, we send a fake GET request to Express only when connection establishes. Can we achieve the goal above by sending fake GET requests on every "message" events?
Hi @roastduck,
Unfortunately this pattern would not be 100% straightforward to include in this library. The GET request for the WS upgrade is actually not fake at all. The WS upgrade request simply is a HTTP GET request. So to handle WS messages the same way would not be possible, since they're not HTTP. We could transform them into fake HTTP requests, but I'm not too fond of that idea. The signatures of HTTP handlers and WS message handlers shouldn't be the same.
There are, however, ways to achieve roughly what you're asking. You could for example build up a separate middleware stack for your WS message handlers. I can provide you an example later this week if that sounds interesting.
I make an attempt to achieve this in pull-request https://github.com/HenningM/express-ws/pull/35 . Please take a look. :)