Writing middleware for Socket.IO
Socket.IO allows us to define two kinds of middleware functions in the server side:
- Namespace middleware: Registers a function that gets executed for every new connected Socket and has the following signature:
namespace.use((socket, next) => { ... })
- Socket middleware: Registers a function that gets executed for every incoming Packet and has the following signature:
socket.use((packet, next) => { ... })
It works similarly to how ExpressJS middleware functions do. We can add new properties to the socket
or packet
objects. Then, we can call next
to pass the control to the next middleware in the chain. If next
is not called, then the socket
won't be connected, or the packet
received.
Getting ready
In this recipe, you will build a Socket.IO server application where you will define middleware functions to restrict access to a certain namespace as well as restricting access to a certain socket based on some criteria. Before you start, create a new...