Working with Session Management
1. Creating Server-Side Sessions
| Component | Detail |
| Session store | Redis, Memcached, DB |
| Session ID | ≥128-bit CSPRNG, opaque |
| Mapping | sessionId → {userId, createdAt, lastSeen, ip, ua, mfa} |
| Transport | HttpOnly cookie |
| Lifecycle | Create on login, rotate on privilege change, destroy on logout |
Example: express-session with Redis
import session from "express-session";
import RedisStore from "connect-redis";
app.use(session({
store: new RedisStore({ client: redis, prefix: "sess:" }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: 1000 * 60 * 60 * 8 // 8 hours
},
name: "__Host-sid"
}));
2. Generating Session IDs
| Requirement | Value |
| Entropy | ≥64 bits (128+ recommended) |
| Source | OS CSPRNG (/dev/urandom, crypto.randomBytes) |
| Encoding | Base64URL or hex |
| Length | 22+ chars (base64) or 32+ (hex) |
| Opacity | No embedded user data |
3. Storing Session Data
| Store | Pros | Cons |
| In-memory | Fast, simple | Lost on restart, no multi-node |
| Redis | Fast, TTL, clustered | Extra infra |
| DB | Durable, queryable | Slower |
| Signed cookie | Stateless | Size limit, harder to revoke |
| JWT | Distributed, stateless | Revocation complexity |
4. Setting Session Expiration
| Type | Typical Value | Behavior |
| Idle timeout | 15–30 min | Reset on activity |
| Absolute timeout | 8–24 hr | Hard cap regardless of activity |
| Remember me | 14–30 days | Long-lived, MFA required to elevate |
| High-privilege | 10–15 min absolute | Re-auth required |
5. Implementing Session Renewal
Example: Sliding expiration
app.use(async (req, res, next) => {
if (req.session?.userId) {
const idle = Date.now() - req.session.lastSeen;
if (idle > IDLE_MS) return req.session.destroy(() => res.status(401).end());
req.session.lastSeen = Date.now(); // extend
await redis.expire(`sess:${req.sessionID}`, ABSOLUTE_TTL);
}
next();
});
6. Destroying Sessions
| Trigger | Action |
| User logout | Delete session row + clear cookie |
| Password change | Invalidate ALL user sessions |
| Role change | Invalidate ALL sessions |
| Admin force-logout | Delete by userId |
| Idle/absolute expiry | TTL auto-deletes |
7. Implementing Session Fixation Protection
Warning: ALWAYS regenerate the session ID after authentication to prevent attackers from pre-setting a known session ID.
Example: Session ID rotation
app.post("/login", async (req, res) => {
const user = await verifyCredentials(req.body);
req.session.regenerate((err) => { // NEW session ID
if (err) return res.status(500).end();
req.session.userId = user.id;
req.session.mfaPassed = false;
res.json({ ok: true });
});
});
8. Using Session Cookies
| Attribute | Value | Reason |
| HttpOnly | true | Blocks JS access (XSS) |
| Secure | true | HTTPS only |
| SameSite | Lax or Strict | CSRF mitigation |
| Path | / | Limit scope |
| Name prefix | __Host- | Forces Secure + path=/ + no Domain |
| Max-Age | Session absolute | Auto-cleanup |
9. Implementing Concurrent Session Control
| Policy | Implementation |
| Single session | Invalidate previous on new login |
| Max N sessions | Track per user, evict oldest |
| Device list | Show user "active sessions" + revoke button |
| Per-device limit | Group by device fingerprint |
10. Handling Session Timeout Warnings
Example: Client warning at T-60s
// poll server-time-aware expiry endpoint
setInterval(async () => {
const { secondsLeft } = await fetch("/api/session/status").then(r => r.json());
if (secondsLeft < 60) showModal("Session expiring. Stay signed in?");
if (secondsLeft <= 0) location.href = "/login?expired=1";
}, 30_000);
11. Implementing Remember Me Functionality
| Aspect | Detail |
| Token type | Separate persistent cookie (not session) |
| Storage | Hashed token in DB with userId + expiry |
| Rotation | Issue new token on each use, invalidate old |
| Reuse detection | If old token reused → revoke chain, alert |
| Privilege | Auto-login = standard session, sensitive ops require re-auth |
12. Preventing Session Hijacking
| Vector | Mitigation |
| XSS | HttpOnly cookie, CSP |
| Network sniff | HTTPS + Secure cookie + HSTS |
| CSRF | SameSite + CSRF token |
| Fixation | Rotate session ID on auth |
| Token theft | Bind to IP/UA, detect anomalies → re-auth |
| Subdomain takeover | Avoid Domain= attribute, use __Host- prefix |