Web Foundations & Databases · beginner · ~11 min

Cookies, sessions, and browser storage

Explain how stateless HTTP tracks logged-in users and the flags that protect session cookies.

Overview

HTTP is stateless; cookies carry a session ID that the server maps to your identity — so the session cookie is a credential. Protect it with HttpOnly/Secure/SameSite. localStorage is JS-readable (XSS-exposed); bearer tokens follow the same "holder = user" rule.

Why it matters

Session cookies and tokens are credentials, so their handling is central to web testing: missing HttpOnly/Secure/SameSite flags, tokens in localStorage, and session-fixation/hijacking are recurring findings.

Core concepts

Stateless HTTP + session ID. Cookie maps to server-side session. Cookie = credential. Stealing it impersonates the user. Flags. HttpOnly (anti-XSS-theft), Secure (HTTPS-only), SameSite (anti-CSRF). localStorage. JS-readable → XSS-exposed. Bearer tokens. Holder is the user.

Lesson

HTTP is stateless — each request is independent. So how does a site remember you're logged in? Cookies.

Cookies and sessions

After login, the server sends a Set-Cookie with a session identifier; the browser returns it on every subsequent request. The server maps that ID to your session (who you are, your privileges). The session cookie is effectively your temporary password — stealing it = impersonating you (session hijacking).

Protective cookie flags (audit these)

  • HttpOnly — JavaScript can't read the cookie, blunting XSS-based theft.
  • Secure — sent only over HTTPS, never cleartext.
  • SameSite (Lax/Strict) — limits cross-site sending, mitigating CSRF. Missing flags on a session cookie is a standard finding.

Browser storage

  • localStorage / sessionStorage — key/value stores readable by JavaScript. Convenient, but anything in localStorage is exposed to XSS — storing tokens there is riskier than an HttpOnly cookie.

Tokens

Some apps use bearer tokens (e.g. JWT) instead of session cookies, sent in an Authorization header. Same rule: whoever holds the token is the user.

Summary

Cookies give stateless HTTP memory by carrying a session ID that is effectively a credential; HttpOnly/Secure/SameSite protect it, while localStorage-stored tokens are XSS-exposed. Credential handling is a core audit area.

Practice with these exercises