Writing
One session across HTTP, SSR and Socket.IO
A session looks like a small thing when the application has one process and one request path. Put a server-rendered frontend, a JSON API and a Socket.IO connection in front of the same user and it becomes a system boundary.
The browser does not know which backend worker handles a request. A page render may go through the frontend server and a proxy. A fetch may take a different path. A websocket may live for hours across deploys, idle periods and network changes. All three paths still need to agree on who the user is and what they are allowed to do.
This is the second problem I wanted to write about from Deadlink Protocol: one session that works across HTTP, server-side rendering and realtime connections, without turning every layer into its own authentication system.
The wrong shape: three authentication systems
The easiest architecture to accidentally build looks like this:
+-------------+ +-------------------+ +------------------+
| HTTP API | | Server-rendered | | Socket.IO |
| checks JWT | | page reads cookie | | trusts userId |
+------+------+ +---------+---------+ +--------+---------+
| | |
`------------------------+--------------------------'
|
three different answers
It usually starts with good intentions. The API gets a token. The SSR layer gets a cookie because it is easier. The socket gets a user ID in the handshake because the client already knows it. Each path works in isolation. Then someone changes a role, bans an account, or logs out, and the three answers stop matching.
A client-supplied user ID is not authentication. A JWT that was valid when the socket connected is not a permission check five hours later. A cookie that the frontend reads for its own state is not automatically the same session the backend will accept.
The shape that works: the backend owns the session
Pick one service as the owner of the session. In a BFF setup that should be the backend, not the rendering layer. The frontend can render pages and proxy requests, but it should not become a second session authority.
+----------+ +------------------+ +------------------+
| Browser | -----> | Frontend / BFF | -----> | Backend HTTP |
| cookie | | forwards cookie | | validates session|
+----+-----+ +------------------+ +----------+-------+
| |
| +------------------+ |
+-----> | Socket.IO | ----------------------> |
| same cookie | validate session |
+------------------+ |
v
+------------------+
| Valkey / Redis |
| session store |
+------------------+
In Deadlink Protocol, the backend owns a signed deadlink_sid cookie and stores the session in Valkey. The frontend runs as a BFF and forwards the cookie. Socket.IO does not invent a second login. It reads the same signed cookie, looks up the same session, and derives the user from it.
That gives the application one answer to three important questions:
Who is this user?
Is the session still alive?
What is this user allowed to do right now?
A small example with one store
Here is the shape of a conventional HTTP session, independent of any particular framework:
const session = require('express-session');
const RedisStore = require('connect-redis').default;
app.use(session({
name: 'app_sid',
secret: process.env.SESSION_SECRET,
store: new RedisStore({ client: redis }),
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000,
},
}));
The important part is not the framework. It is the contract: the cookie points at a server-side session, the store is shared by every worker, and the client cannot edit the session contents.
Now reuse that contract in the socket layer:
io.use(async (socket, next) => {
const cookieHeader = socket.request.headers.cookie;
const signedId = readCookie(cookieHeader, 'app_sid');
const sessionId = unsignCookie(signedId, process.env.SESSION_SECRET);
const session = await redis.get(`session:${sessionId}`);
if (!session) {
return next(new Error('unauthorized'));
}
const data = JSON.parse(session);
socket.data.userId = data.userId;
next();
});
The socket has no separate login token and no client-provided user ID. The HTTP route and the socket both resolve the same session record. If the session is deleted, both paths lose access.
There is still an important distinction: authenticating the socket is not the same as authorizing every event. Resolve the permission for each action, especially for moderation or admin namespaces.
Make logout and bans reach every connection
Deleting the session is only half of a logout. The other half is closing connections that are still open.
+-------------+ +---------------------+
| logout | ----> | delete session |
| request | | from shared store |
+------+------+ +----------+----------+
| |
| v
| +----------------------+
`------------> | disconnect sockets |
| in user:<userId> |
+----------------------+
With multiple workers, a socket may be connected to a process that did not handle the logout. That is why the disconnect has to go through the socket server's shared adapter, not through a local list of sockets in the current process.
async function revokeUser(userId) {
await sessionStore.deleteByUserId(userId);
io.in(`user:${userId}`).disconnectSockets(true);
}
Do both operations independently. If the session deletion is best-effort and the socket eviction is best-effort, a failure in one should still be visible. A ban that removes the database row but leaves a live socket is a security bug with a very long tail.
Permissions change after login
Session data is a snapshot. If an administrator removes a role, the user's cookie does not automatically become less powerful. You need either a short session lifetime or an explicit permission version.
A version check can be small:
async function requirePermission(session, key) {
const current = await permissionStore.version(session.userId);
if (current !== session.permissionVersion) {
await refreshSessionPermissions(session);
}
if (!session.permissions.includes(key)) {
throw new Error('forbidden');
}
}
The exact storage format is up to you. The invariant is that an authorization decision reads the current grant state or a version that changes when grants change. A role name inside a ten-hour-old websocket payload is not enough.
This also applies to staff routes. If staff access is protected by a second factor, the socket transport should apply the same gate as HTTP. It is easy to protect the REST endpoint and forget that the moderation namespace is another door into the same building.
What happens when the shared store is down
A shared session store is a dependency. You need to decide what degraded behavior means before it happens.
Path Store unavailable Possible policy
------------------- ---------------------- -------------------------------
Normal page No session lookup Controlled error or signed-out page
API write Cannot verify user Fail closed
Socket handshake Cannot verify cookie Reject new connections
Socket event Permission cache missing Use bounded fallback or reject
Rate limiting Shared counters missing Keep a bounded per-process limiter
There is no universal answer, but there must be an explicit one. Failing open on a system that spends money or grants moderation powers is different from failing open on a public status page. Write the decision down and test the failure path.
Cookie and proxy details that break sessions
Most session bugs I have seen are not exotic. They are deployment details:
The cookie is set on
example.combut the API runs onapi.example.com.The BFF forwards the body but drops the cookie header.
The proxy terminates TLS and the app forgets to trust the forwarded protocol.
The app runs behind an HTTP proxy and sets
secureincorrectly in one environment.A wildcard CORS rule is used because the cookie was not working.
The session cookie is available to JavaScript when it should be
httpOnly.Multiple domains create multiple sessions for what users think is one login.
Write down the cookie domain, path and SameSite policy. Test the same flow through the proxy, not only against the local backend port. A session that works in development but fails after TLS termination is a deployment problem pretending to be an auth problem.
The checklist I would use again
One service owns the session.
The session store is shared by every worker.
HTTP, SSR and Socket.IO resolve the same cookie and session record.
No user ID is trusted from a socket handshake.
Permissions are checked per action or refreshed through a version.
Logout and bans delete the session and disconnect all sockets.
Socket eviction goes through the shared adapter.
Valkey failure behavior is defined and tested.
Cookie flags, domain and proxy headers are tested through the real entry point.
A session is not a login form. It is a contract between the browser, the rendering layer, the API and the realtime server. Make the contract explicit, give it one owner, and the rest of the system becomes much easier to reason about.