Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.IO middleware, io.use

Working on a web application which is built upon expressJS and Socket.io. In the following post I saw the usage of middleware syntax which was new to me. Here is an example of the syntax:

const io = require('socket.io')();

io.use(function(socket, next) {
  // execute some code
  next();
})
.on('connection', function(socket) {
    // Connection now authenticated to receive further events

    socket.on('message', function(message) {
        io.emit('message', message);
    });
});

It basically uses middleware functions on the socket.io instance. My previous understanding was that middlware can only be used on the express instance (app.use(...)).

Questions:

  1. Is this syntax just regular middleware which works similarly to app.use(...)?
  2. If it is different, what are the differences?
like image 240
Willem van der Veen Avatar asked Apr 24 '18 14:04

Willem van der Veen


1 Answers

io.use() allows you to specify a function that is called for every new, incoming socket.io connection. It can be used for a wide variety of things such as:

  1. Logging
  2. Authentication
  3. Managing sessions
  4. Rate limiting
  5. Connection validation

And so on...

It's purpose is similar to Express middleware (like with app.use()), but this is for incoming socket.io connections, not incoming the regular http requests that Express manages. If you want middleware to process an incoming http request, use Express middleware with app.use(). If you want middleware to process an incoming socket.io connection, use socket.io middleware with io.use().

like image 65
jfriend00 Avatar answered Oct 21 '22 14:10

jfriend00