Socket.IO middleware, io.use

According to the official documentation of socket.io V 3.0.4 a middleware function io.use in socket.io is a function that gets executed for every incoming connection like in Express but the only difference is that socket manages the request wherein express HTTP protocol manages the request.

Why socket middleware

  • Middleware functions in socket.io are very useful during authentication of request,
  • Additional data like credentials can be put in the socket during the connection.
  • Middleware function can be used multiple times where each of them runs the given function in order.

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().