On this page
Middlewares
A middleware function is a function that gets executed for every incoming connection.
Middleware functions can be useful for:
- logging
- authentication / authorization
- rate limiting
Note: this function will be executed only once per connection (even if the connection consists in multiple HTTP requests).
Registering a middleware
A middleware function has access to the Socket instance and to the next registered middleware function.
|
You can register several middleware functions, and they will be executed sequentially:
|
Please make sure to call next()
in any case. Otherwise, the connection will be left hanging until it is closed after a given timeout.
Sending credentials
The client can send credentials with the auth
option:
|
Those credentials can be accessed in the handshake object on the server-side:
|
Handling middleware error
If the next
method is called with an Error object, the connection will be refused and the client will receive an connect_error
event.
|
You can attach additional details to the Error object:
|
Compatibility with Express middleware
Most existing Express middleware modules should be compatible with Socket.IO, you just need a little wrapper function to make the method signatures match:
|
The middleware functions that end the request-response cycle and do not call next()
will not work though.
Example with express-session:
|
Example with Passport:
|
A complete example with Passport can be found here.
© 2014–2021 Automattic
Licensed under the MIT License.
https://socket.io/docs/v3/middlewares