Implementing Session Management
1. Creating Session ID
| Generator | Notes |
|---|---|
crypto.randomUUID() | v4, browser+Node |
nanoid() | Shorter, URL-safe |
| Server-issued | Tie to authenticated user |
2. Storing Session Data
| Store | Detail |
|---|---|
| In-memory Map | Single node only |
| Redis | Shared, fast, TTL |
| Cookie + signed | Stateless; size-limited |
| JWT | Self-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
| Trigger | Action |
|---|---|
| TTL elapsed | Close 4401 |
| Idle timeout | Close 4002 |
| Token refresh fails | Force re-auth |
| Admin revoke | Close all sockets for user |
5. Implementing Session Persistence
| Store | Pros / Cons |
|---|---|
| Redis | Fast, TTL native |
| Memcached | Simple cache |
| Database | Durable, slower |
| JWT | No server lookup; can't revoke easily |
6. Managing Multiple Sessions
| Scenario | Detail |
|---|---|
| Multiple devices | Map user → Set<sessionId> |
| Multiple tabs | Use SharedWorker / BroadcastChannel |
| Concurrent sockets | Index 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
| Approach | Detail |
|---|---|
| Central Redis | Lookup per upgrade |
| Signed JWT | Validate locally |
| Sticky session + sync | Pin client; replicate state |
9. Implementing Session Heartbeat
| Mechanism | Detail |
|---|---|
| Touch on activity | Refresh TTL on each message |
| Periodic ping | Touch every N seconds |
| Pause when hidden | Allow idle timeout |
10. Auditing Session Activity
| Event | Log Field |
|---|---|
| Login | userId, ip, ua, ts |
| WS connect | sessionId, sockId |
| Sensitive action | method, params hash |
| Logout / revoke | reason, actor |