Lesson 7 / 25
Server-Side Sessions
An opaque ID in a cookie, state on the server.
How server-side sessions work
At login the server creates a session record (user ID, creation time, last activity, maybe MFA status) in a store such as Redis or a database, and sends the browser an opaque, random session ID in a cookie. On each request the server looks the ID up. Because the state lives on the server, revocation is immediate: delete the record and the session is gone. The session ID must come from a CSPRNG with enough entropy (OWASP suggests at least 64 bits of entropy) and must not encode user data. Frameworks provide this, so use theirs rather than inventing a scheme.
Remembering who logged in
After login, the server needs a safe way to recognise the same user on later requests.
express-session with Redis
A typical configuration (check the connect-redis docs for the import style of your version).
import session from 'express-session';
import { RedisStore } from 'connect-redis';
app.set('trust proxy', 1); // behind a TLS-terminating proxy
app.use(session({
name: '__Host-sid', // __Host- prefix: Secure, Path=/, no Domain
secret: process.env.SESSION_SECRET!, // signs the cookie value
store: new RedisStore({ client: redisClient }),
resave: false,
saveUninitialized: false, // no session until something is stored
cookie: {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 8 * 60 * 60 * 1000, // 8 hours
},
}));A cloakroom ticket
You hand over your coat and get a numbered ticket. The ticket itself says nothing about the coat; the cloakroom keeps the details. If the ticket is lost, staff can cancel that number instantly.
Quick check: What is a key advantage of server-side sessions over self-contained tokens?
- Sessions can be revoked immediately by deleting the server record
- They never need a cookie
- They work without any server storage
- They cannot be stolen
Answer
Sessions can be revoked immediately by deleting the server record — State on the server means the server decides when a session ends.