Register Authentication Middleware

Now register the authentication middleware in src/config/socket.js.

Socket.IO allows middleware to be registered using io.use().

After registration, connections without valid tokens will be rejected.

Updated src/config/socket.js
import { Server } from 'socket.io';
import { socketAuth } from '../middleware/socket-auth.js';

export function initializeSocket(httpServer) {
  const io = new Server(httpServer);

  io.use(socketAuth);

  return io;
}

Registers the authentication middleware before the application starts accepting authenticated Socket.IO connections.

Key Takeaways
  • io.use() registers Socket.IO middleware.

  • Authentication middleware runs during connection establishment.

  • Invalid connections are rejected before the connection event executes.