9

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
});
1

2 Answers 2

9

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"
0
0

The npm module socket.io-events can help you. The npm repository is well documented.

var router = require('socket.io-events')();

// handles all events 
router.on(function (socket, args, next) {
  next();
});

var io = require('socket.io')(3000);
io.use(router);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.