Right now you can bind middleware to io.use(middleware);
, but this is triggered only when a socket connection is made. Is there a way to intercept it before passing it to an event handle like in expressjs?
In other word....
In express.js you can do:
app.get('/', middleware1, middleware2, function(req, res){
res.end();
});
Can I do the same in socket.io?
socket.on('someEvent', middleware1, middleware2, function(data){
console.log(data); // data is now filtered by 2 previous middlewares
});
As of Socket.io v2.0.4 (found this while inspecting this) you can use a socket middleware like so:
io.on('connection', (socket) => {
socket.use((packet, next) => {
// Handler
next();
});
});
Which means that you can set your code like so:
io.on('connection', (socket) => {
socket.use((packet,next) => {
if (packet[0] === 'someEvent') {
if (authorizationCondition) {
return next(new Error('nope'))
}
}
next();
})
socket.on('someEvent', function(data){
console.log(data);
});
})
You will then be able to catch errors like this with a client-side
io.on('error', err => { ... }) // err will equal "nope"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With