100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Authentication and the Handshake

Understand the Socket.IO handshake process and how to securely authenticate clients using the auth payload, middleware, and token renewal on reconnect.

Advanced Socket.IOIntermediate10 min readJul 10, 2026
Analogies

Understanding the Socket.IO Handshake

The handshake is the initial exchange that happens when a client attempts to connect: the client sends an HTTP request (or WebSocket upgrade request) carrying query parameters, headers, and an optional auth object, and the server responds with a session ID and confirms the connection or rejects it. This entire exchange is captured on the server as socket.handshake, an object containing headers, time, address, xdomain, secure, issued, url, query, and crucially auth — the payload the client explicitly sends for authentication purposes, separate from generic query strings.

🏏

Cricket analogy: The handshake is like the toss before a match — a brief, formal exchange (captain's call, coin flip) that determines terms before the actual game (data exchange) begins.

Passing Auth Data from the Client

Clients pass authentication data using the dedicated auth option in the client constructor: io('https://api.example.com', { auth: { token: myJwt } }). Unlike query parameters, which are visible in server logs and proxy access logs by default, the auth object is sent as part of the initial handshake payload and can be easily updated before a reconnection attempt by mutating socket.auth (as a function or object) so a fresh token is sent on every reconnect rather than the original, possibly-expired one.

🏏

Cricket analogy: It's like a player's accreditation lanyard (auth token) shown discreetly at the team entrance, distinct from the public ticket stub (query params) anyone can see at the general gate.

javascript
// Client: send a token via the dedicated auth option
const socket = io('https://api.example.com', {
  auth: (cb) => {
    cb({ token: localStorage.getItem('jwt') });
  }
});

// Server: verify the token in middleware
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) return next(new Error('Authentication failed'));
    socket.data.user = decoded;
    next();
  });
});

Verifying Tokens in Middleware

The standard pattern is to verify a JWT (or session cookie) inside an io.use() middleware, decoding the token with a library like jsonwebtoken and attaching the resulting user object to socket.data.user so every subsequent event handler can read the authenticated identity without re-verifying. Because middleware runs before any event listener, this guarantees no business logic executes for an unauthenticated socket — but it's important to also re-check authorization (not just authentication) per-event if actions have different permission levels, since the initial handshake only proves who the user is, not what they're allowed to do on every subsequent action.

🏏

Cricket analogy: It's like verifying a player's central contract once at the season's start, then still checking match-specific fitness clearance before each individual game — identity once, authorization per event.

Handling Reconnection and Token Renewal

Socket.IO's client automatically attempts reconnection after a disconnect, and each reconnection attempt re-runs the full handshake, meaning stale or expired tokens sent as a plain object will fail authentication on reconnect unless refreshed. The recommended pattern is to set socket.auth to a function rather than a static object; the client then invokes this function immediately before every connection and reconnection attempt, letting you fetch a fresh token (e.g., from a refresh-token flow) each time rather than being stuck with the token captured at initial page load.

🏏

Cricket analogy: It's like a player's fitness clearance needing re-certification before every match of a series, not just once at the tour's start, since injuries and conditions change.

Using a function for socket.auth (auth: (cb) => cb({ token: getFreshToken() })) rather than a static object is the key pattern for handling token expiry gracefully across reconnects — it's invoked fresh on every single connection attempt, automatic reconnections included.

  • The handshake is the initial connect exchange, captured server-side as socket.handshake with headers, query, and auth data.
  • The dedicated auth option is the correct channel for credentials, distinct from publicly visible query parameters.
  • Token verification belongs in io.use() middleware, running before any event handler executes.
  • Authentication (who you are) is proven at the handshake; authorization (what you can do) should still be checked per sensitive event.
  • Socket.IO automatically re-runs the full handshake on every reconnection attempt.
  • Setting socket.auth as a function ensures a fresh token is sent on every connect and reconnect, not a stale cached one.
  • socket.data is the recommended place to store the authenticated user object for later handlers to read.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#SocketIOStudyNotes#AuthenticationAndTheHandshake#Authentication#Handshake#Socket#Passing#Security#StudyNotes#SkillVeris