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.
io.use((socket, next) => { |
You can register several middleware functions, and they will be executed sequentially:
io.use((socket, next) => { |
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:
// plain object |
Those credentials can be accessed in the handshake object on the server-side:
io.use((socket, next) => { |
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.
// client-side |
You can attach additional details to the Error object:
// server-side |
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:
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next); |
The middleware functions that end the request-response cycle and do not call next()
will not work though.
Example with express-session:
const session = require("express-session"); |
Example with Passport:
const session = require("express-session"); |
A complete example with Passport can be found here.