Understand Socket.IO Handshake Authentication

A real-time application should not allow every visitor to perform protected actions.

For example, consider a private messaging application. Users should only be allowed to:

  • Connect with a valid identity.
  • Join rooms they have permission to access.
  • Send messages as their authenticated account.
  • Receive private notifications intended for them.

Socket.IO provides middleware through io.use().

This middleware runs during the connection process, before the connection is fully established.

The client can provide authentication data through the auth option.

For example:

const socket = io({
  auth: {
    token: accessToken
  }
});

On the server, this value can be accessed through socket.handshake.auth.

The server must verify the token rather than trusting the value supplied by the browser.

Socket.IO Authentication Flow
Key Takeaways
  • Socket.IO middleware runs before the connection is accepted.

  • The client can send credentials through the auth option.

  • The server must verify credentials independently.