Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Middleware and Authentication

Socket.IO Middleware: Intercepting Connections

Learn Socket.IO middleware. Run code before a connection is accepted with io.use, reject with next(err), pass error data to the client, order middleware, use packet middleware and reuse Express middleware.

A middleware is a function that runs before something is allowed to happen, and can either let it continue or stop it. If you have used Express, the idea is the same: a chain of functions, each calling next() to pass control on. In Socket.IO the thing being intercepted is a connection attempt. Middleware is where you check credentials, attach information to the socket, log, rate-limit, and refuse unwanted clients before your connection handler ever runs.

io.use

Register middleware with io.use(fn) (or namespace.use(fn) for one namespace). The function receives the socket that is trying to connect and a next callback:

JavaScript
io.use((socket, next) => {
  // look at socket.handshake: auth, headers, query, address...
  const token = socket.handshake.auth.token;
  if (!token) {
    return next(new Error('missing token')); // refuse
  }
  socket.data.userId = decode(token);         // attach information
  next();                                     // accept: go to the next middleware
});

Key rules:

  1. Always call next exactly once, either next() or next(error). If you forget, the client hangs until connectTimeout (45 s) and then gets disconnected.
  2. Middleware functions run in the order they were registered, one after the other. The first to call next(error) ends the chain: later ones do not run.
  3. At this stage the socket is not yet connected. You cannot emit to it and the connection event has not fired. Rooms cannot be joined meaningfully until connection.
  4. If all middleware calls next(), the connection is accepted and connection fires.

What the client sees

When middleware calls next(err), the client receives a connect_error event whose argument has err.message and, if you set it, err.data (any JSON data):

JavaScript
// server
const error = new Error('not authorized');
error.data = { code: 'TOKEN_EXPIRED', retryAfter: 30 };
next(error);

// client
socket.on('connect_error', (err) => {
  console.log(err.message); // "not authorized"
  console.log(err.data);    // { code: 'TOKEN_EXPIRED', retryAfter: 30 }
});

Importantly, a refusal from middleware does not trigger automatic reconnection. The client stays disconnected, because retrying with the same credentials would fail again. (Network errors, where the server is unreachable, do trigger retries.)

Watching the chain run

Node.js Middleware order and rejection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For ana all three middleware run and connection fires. For the empty auth object the chain stops at [2], and the client receives the error with its data. For mallory the chain reaches [3].

Never put secrets in the err.message or err.data you send back (for example stack traces or internal ids). Attackers read these. Send a short, safe message and a code your client understands.

Async middleware

Middleware often needs a database or an HTTP call, for example to look up a session. Calling next after the awaited work is the safe pattern, and wrapping it in try/catch prevents a thrown error from leaving the client hanging:

JavaScript
io.use(async (socket, next) => {
  try {
    const user = await findUserByToken(socket.handshake.auth.token);
    if (!user) return next(new Error('invalid token'));
    socket.data.user = user;
    next();
  } catch (err) {
    next(new Error('server error')); // do not leak err.message
  }
});

Keep middleware fast. It runs for every connection attempt, including reconnection storms after a restart.

Packet middleware: socket.use

There is a second kind of middleware that runs for every incoming event on one connected socket, not only at connection time. Register it inside the connection handler with socket.use; it receives the packet as an array [eventName, ...args]:

JavaScript
io.on('connection', (socket) => {
  socket.use(([event, ...args], next) => {
    if (isBlocked(socket, event)) return next(new Error('rate limited'));
    next();
  });

  socket.on('error', (err) => {
    // errors passed to next(err) arrive here
    socket.emit('app:error', err.message);
  });
});

When a packet middleware calls next(err), the event handler is skipped and the error is delivered to the socket's error event. It is a good place for logging, rate limiting and shared validation. The pipeline pattern itself is plain JavaScript, so we can run it without any library:

Node.js A middleware pipeline for packets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note that the logger sees every packet, even the ones that are blocked later in the chain, because it comes first.

Reusing Express middleware

Many Express middleware functions (sessions, passport, cors, helmet) can be adapted with a one-line wrapper, since the socket exposes the raw request at socket.request:

JavaScript
const wrap = (middleware) => (socket, next) => middleware(socket.request, {}, next);

io.use(wrap(sessionMiddleware));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));

io.use((socket, next) => {
  if (socket.request.user) return next();
  next(new Error('unauthorized'));
});

Note that session middleware needs the req object only; the {} stands in for a response, so middleware that writes responses will not work. For middleware that should run on every Engine.IO request (including long-polling requests and the WebSocket upgrade, for example to set cookies), use io.engine.use(middleware) instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if a connection middleware never calls next()?

    The chain never finishes, so the connection stays pending until the connectTimeout (45 s by default).
  2. 2. How does a client learn why middleware rejected it?

    next(err) becomes connect_error on the client, and err.data can carry extra JSON information.
  3. 3. In which order do io.use middleware functions run?

    They form a chain; the first next(err) ends it and later functions do not run.
  4. 4. Which tool runs code on every incoming event of a connected socket?

    socket.use registers packet-level middleware; io.use only runs when a connection is being established.

Summary

  • io.use((socket, next) => ...) runs before connection; call next() to accept or next(error) to refuse, exactly once.
  • Middleware runs in registration order; per-namespace middleware uses namespace.use.
  • Rejections reach the client as connect_error with message and optional data, and are not retried automatically.
  • socket.use is per-event middleware for logging, validation and rate limiting.
  • Express middleware can be wrapped with middleware(socket.request, {}, next); io.engine.use runs per HTTP request.

Next: Authentication During the Handshake