Implementing Session Management

1. Creating Session ID

GeneratorNotes
crypto.randomUUID()v4, browser+Node
nanoid()Shorter, URL-safe
Server-issuedTie to authenticated user

2. Storing Session Data

StoreDetail
In-memory MapSingle node only
RedisShared, fast, TTL
Cookie + signedStateless; size-limited
JWTSelf-contained, no lookup

3. Associating Session with Connection

Example: Bind on upgrade

httpServer.on("upgrade", async (req, sock, head) => {
  const sid = parseCookie(req.headers.cookie)?.sid;
  const session = await sessions.get(sid);
  if (!session) return sock.destroy();
  wss.handleUpgrade(req, sock, head, (ws) => {
    ws.session = session;
    wss.emit("connection", ws, req);
  });
});

4. Handling Session Expiration

TriggerAction
TTL elapsedClose 4401
Idle timeoutClose 4002
Token refresh failsForce re-auth
Admin revokeClose all sockets for user

5. Implementing Session Persistence

StorePros / Cons
RedisFast, TTL native
MemcachedSimple cache
DatabaseDurable, slower
JWTNo server lookup; can't revoke easily

6. Managing Multiple Sessions

ScenarioDetail
Multiple devicesMap user → Set<sessionId>
Multiple tabsUse SharedWorker / BroadcastChannel
Concurrent socketsIndex by (userId, deviceId)

7. Invalidating Sessions

Example: Force logout

async function logoutUser(userId) {
  await sessions.deleteByUser(userId);
  for (const c of wss.clients) {
    if (c.session?.userId === userId) c.close(4401, "logout");
  }
}

8. Sharing Sessions Across Servers

ApproachDetail
Central RedisLookup per upgrade
Signed JWTValidate locally
Sticky session + syncPin client; replicate state

9. Implementing Session Heartbeat

MechanismDetail
Touch on activityRefresh TTL on each message
Periodic pingTouch every N seconds
Pause when hiddenAllow idle timeout

10. Auditing Session Activity

EventLog Field
LoginuserId, ip, ua, ts
WS connectsessionId, sockId
Sensitive actionmethod, params hash
Logout / revokereason, actor