Sessions and Cookies in Practice

Intermediate · 21 min

The Set-Cookie flags that actually protect a login session, and where server-side session data should live once you have more than one server.

Before thisPassword Hashing and Credential Storage

Theo - t3.gg · 21 min

Sessions and Cookies in Practice

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Theo - t3.ggReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • HTTP has no memory between requests, so a session only works because the server hands the browser an opaque ID in a cookie and the browser dutifully attaches it to every subsequent request.
  • `HttpOnly` stops JavaScript from reading the cookie, which is the difference between an XSS bug being annoying and an XSS bug handing an attacker a live logged-in session.
  • `Secure` and `SameSite` close two different holes — one stops the cookie from ever crossing the network in plaintext, the other stops it from being sent along with a request a different site tricked the browser into making.
  • A session store that lives in one server's memory works fine for one server and breaks the moment you run two, because the load balancer has no idea which instance remembers which user.

The problem a session actually solves

HTTP is stateless by design: the server that handles your login request has no built-in memory of you by the time your next request arrives. That next request might even land on a different server entirely. So the moment a user logs in, you need some way to attach “this request came from the person who just authenticated” to every request that follows, without asking them to type their password again each time.

A session is the standard answer. The server creates a record — “user 4821 is logged in, session started at this time” — gives it a random, unguessable ID, and hands that ID to the browser in a cookie. The browser’s job (which it does automatically, no application code required) is to attach that cookie to every subsequent request to the same domain. The server’s job on each request is to look up the ID, find the matching session record, and know who’s asking. The cookie itself carries almost no information — it’s just a key into a lookup table that lives on the server.

This is also why a stolen session cookie is equivalent to a stolen login: whoever holds that ID can make requests that look exactly like the real user, with no password required. Everything below exists to make that cookie harder to steal and the lookup it points to actually workable once you’re running more than one server.

The embedded video spends its time on a different but related problem — the fact that “authentication” gets talked about as something more exotic than it is, and that a lot of what people argue about under that name (which package to install, how JWTs get issued) isn’t really the authentication step at all. It’s good framing for why a session is just “the server remembers you, and a cookie says who you are” rather than something to reach for a library to avoid understanding. The concrete mechanics — the specific cookie flags and where session data should live once you scale past one server — are this lesson’s job, covered below.

When the server sends the session cookie, the response header looks something like this:

Set-Cookie: session_id=a1b2c3d4...; HttpOnly; Secure; SameSite=Lax; Path=/

Three of those attributes are doing real security work, and it’s worth knowing exactly what each one blocks, because “set all three” is good advice but “I don’t know what any of them do” is how you end up disabling one the day it becomes inconvenient.

HttpOnly tells the browser to hide this cookie from JavaScript entirely — document.cookie simply won’t include it. This matters because of cross-site scripting (XSS): if an attacker manages to inject a script into your page (through an unescaped comment field, a vulnerable dependency, whatever the hole turns out to be), that script runs with the same access to the page as your own code. Without HttpOnly, that injected script can read the session cookie and send it straight to an attacker’s server, turning a markup bug into a full account takeover. HttpOnly doesn’t fix the XSS bug — you still have to fix that — but it means the specific worst outcome, a stolen live session, isn’t automatic.

Secure means the browser will only ever send this cookie over HTTPS, never plain HTTP. Without it, if a user ever hits an http:// URL for your domain — an old bookmark, a typed-in address without the s, a request on public wifi that gets downgraded — the cookie goes out in plaintext, readable by anyone on the same network. Modern setups that redirect everything to HTTPS anyway should still set Secure explicitly: it’s a backstop, not a convenience.

SameSite controls whether the browser attaches the cookie to a request that originated from a different site. This is the defense against cross-site request forgery (CSRF): without it, a malicious page you visit can embed a form that silently submits to your-bank.com/transfer, and your browser — having no concept of “this request looks suspicious” — happily attaches your real session cookie to it, because as far as the browser’s older rules were concerned, a request to your-bank.com is a request to your-bank.com no matter where it was triggered from. SameSite=Lax (the sensible default for most apps) still allows the cookie on top-level navigation, like clicking a link, but blocks it on cross-site form submissions and background requests. SameSite=Strict blocks it even on navigation from an external link, which is more locked-down but can break flows like “click an email link and land already logged in.” SameSite=None disables the protection entirely and is only for the rare case of a cookie that genuinely needs to work across sites (an embedded third-party widget, for instance) — and browsers require Secure to be set alongside it, or they’ll reject the cookie outright.

Where the session data actually lives

The cookie is just an ID. The interesting question is where the record that ID points to — “this ID belongs to user 4821, logged in at this time, with these permissions” — actually lives, and the answer that works changes the moment you stop running a single server.

In-memory, meaning a plain data structure inside your running application process, is the simplest option and genuinely fine while you’re running exactly one instance. It’s fast, it requires no extra infrastructure, and most frameworks default to it for local development. The problem shows up the instant you add a second instance behind a load balancer: server A has no visibility into server B’s memory, so a user whose session lives on A gets treated as a stranger the moment a request routes to B. Restarting the single instance also wipes every logged-in user’s session at once, since the data never left process memory in the first place.

A shared store, most commonly Redis, fixes this by moving session data out of any individual process and into something every instance can read and write. Now the cookie’s ID is a lookup key against a store that’s the same no matter which server instance answers the request — add a third instance, restart one of them, it doesn’t matter, because none of them were ever the source of truth. Redis specifically fits well here because sessions are small, read constantly, and naturally expire: Redis’s built-in per-key expiration means an idle session can simply time out and vanish without you writing cleanup code for it.

The practical rule: build locally with whatever your framework defaults to, but the moment you’re deploying more than one instance of your service — which is most production deployments past the earliest stage — a shared session store isn’t an optimization, it’s a correctness requirement. Without it, “getting logged out randomly” isn’t a bug report you’ll be able to reproduce reliably; it’ll just be Tuesday for a fraction of your users.

What this lesson isn’t

Everything above assumes you’ve already decided sessions are the right auth mechanism and covers implementing them correctly. The separate question of whether to use a session cookie at all versus a JWT or an API key — which one fits a browser-based app, a mobile client, or a machine-to-machine integration — is a design decision covered in JWT, API Keys, and Session Auth. Read that one first if you haven’t picked an auth scheme yet; come back here once you have.

Check yourself

  1. 01Why does logging a user in require a cookie at all, instead of the server just remembering who's logged in?

    HTTP requests are independent of each other by design — the server has no built-in way to know that request #2 came from the same browser as request #1. A cookie is the mechanism that carries an identifier across that gap: the server hands it out once, and the browser automatically attaches it to every request to that domain afterward.

  2. 02What specific attack does `HttpOnly` block, and what does it not block?

    `HttpOnly` stops JavaScript running on the page from reading `document.cookie`, which means a cross-site scripting bug that injects a malicious script can't simply read the session cookie and ship it off to an attacker's server. It doesn't stop the cookie from being sent on requests, and it doesn't fix the underlying XSS vulnerability — it just limits one specific thing an attacker can do once they've found one.

  3. 03Why isn't `Secure` enough on its own to protect a session cookie, and what does `SameSite` add?

    `Secure` only guarantees the cookie travels over HTTPS instead of plaintext HTTP — it says nothing about who the request came from. `SameSite` controls whether the browser attaches the cookie to a request triggered by a different site at all, which is what actually blocks a cross-site request forgery attack where a malicious page tries to make your browser hit your bank's transfer endpoint using your still-valid session cookie.

  4. 04Why does an in-memory session store break the moment you add a second server instance?

    If server A stores a user's session in a local dictionary in its own process memory, server B has no way to see it. A load balancer splitting traffic between the two will route that user's next request to server B about half the time, and server B will have no idea who they are — the user effectively gets logged out at random. A shared store that every instance can read from fixes this because it isn't tied to any one process.

  5. 05What's the difference between this lesson's scope and jwt-api-keys-and-session-auth in the api-design roadmap?

    The api-design lesson is about the decision of which auth scheme to use at all — session, JWT, or API key — and the tradeoffs between them as an architectural choice. This lesson assumes you already picked sessions and covers the mechanics of doing that correctly: the cookie flags that actually matter and where the session data physically lives as you scale.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark