2.2.5.2 Authentication via Socket.io

Approach:

• Require clients to provide a JWT token in the connection handshake.

• Verify token server-side; reject unauthorized sockets.

// Add this logic inside socketServer.js:
io.use((socket, next) => {
  const token = socket.handshake.auth?.token;
  if (!token) return next(new Error('No token'));

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    socket.user = decoded;
    next();
  } catch (err) {
    next(new Error('Invalid token'));
  }
});

Last updated