--- title: "JWT vs Session Cookies: What to Use and When" author: "Ankit Singh" published: "2026-11-30T04:40:00.066Z" updated: "2026-11-30T04:25:52.902Z" url: "https://zyvop.com/jwt-vs-session-cookies-what-to-use-and-when-bmh41" canonical: "https://zyvop.com/jwt-vs-session-cookies-what-to-use-and-when-bmh41" tags: ["Web Security","authentication","cookies","session management","jwt"] --- # JWT vs Session Cookies: What to Use and When Cookies and JWTs aren't opposites. Here's how sessions and tokens really differ, what the latest IETF guidance says, and which to pick for web apps, SPAs, mobile apps and APIs. ![Cover image]() Every few months someone declares JWTs better than sessions, and someone else declares the opposite. Both are usually answering the wrong question. A **cookie** is a way for the browser to store a value and send it back automatically. A **session** is state your server keeps, found with an opaque ID. A **JWT** is a signed bundle of claims. These sit on different axes. You can put a JWT in a cookie, and you can send a session ID in a header. The real questions are two. Where does the truth about a login live: on your server, or inside the token? And where does the browser keep the credential: somewhere scripts can read it, or somewhere they can't? This is the first post in an auth series, after the one on password storage. It gives a recommendation for each kind of app, then tested code for the three building blocks. > **Sources:** the advice comes from OWASP's Session Management and JSON Web Token cheat sheets, OWASP's ASVS, RFC 8725 (JWT best practices), RFC 10017 (OAuth 2.0 for browser-based apps, published in August 2026) and MDN. Standards in this area are still being revised, so check the current versions. * * * ## The short answer | What you're building | Use | Why | | --- | --- | --- | | A web app with its own backend (server-rendered, or a single-page app on the same site) | **Server-side session in an HttpOnly cookie** | Instant revocation, and scripts can't read the credential | | A single-page app that uses OAuth or third-party APIs | **A backend-for-frontend (BFF)**: tokens stay on the server, the browser gets a session cookie | The IETF strongly recommends it for business, sensitive and personal-data apps | | A mobile or native app | **Short-lived access token plus rotating refresh token** | No browser cookie jar. OAuth's code flow with PKCE is the standard route | | Service-to-service calls | **Short-lived signed JWT**, verified locally | Many services can check it without calling an auth server | | Third-party API access | **OAuth access tokens** (JWT or opaque) | Built for delegated access | If you're unsure, start with the first row. OWASP's own JWT cheat sheet suggests considering a plain session system before reaching for JWTs, and RFC 10017 says simple applications are often made needlessly complex by using OAuth in place of session management. ```mermaid flowchart TD A["What are you building?"] --> B{"Browser app with
your own backend?"} B -- Yes --> C{"Calls third-party or
OAuth-protected APIs?"} C -- No --> S["Server-side session
in an HttpOnly cookie"] C -- Yes --> F["BFF: tokens on the server,
session cookie in the browser"] B -- No --> D{"Native app or
service-to-service?"} D -- Yes --> J["Short-lived JWT access token
+ rotating refresh token"] D -- No --> O["Third-party API access:
OAuth access tokens"] ``` * * * ## How they really differ | | Server-side session | Signed JWT | | --- | --- | --- | | What the client holds | A random, meaningless ID | The claims themselves, readable by anyone who has the token | | Where the truth lives | Your session store | In the token, checked with a key | | Logout or revoke | Immediate | Not until it expires, unless you add state | | Permission changes | Apply on the next request | Stale until the token expires | | Cost per request | A store lookup | A signature check, no lookup | | Size | Tiny | Grows with the claims. A single cookie tops out around 4 KB | | Main risks | Session fixation, CSRF, store availability | Algorithm tricks, weak keys, no revocation, theft from storage | A signed JWT is not encrypted. Anyone holding it can read the claims, so don't put secrets in them. * * * ## Two myths ### "JWTs scale better" They skip a lookup, and that's a real saving. But the moment you need a working logout, "log out everywhere" after a password change, or a role change that takes effect now, you need state again: a deny list, or a refresh-token database. Here is the difference, from the code later in this post: ```text logout at 60 seconds: session cookie -> rejected immediately access token -> still valid for 540 more seconds ``` The session dies on the next request. The access token lives on until it expires. Short lifetimes shrink that window, and they can't close it. ### "Just store the JWT in localStorage" RFC 10017 is blunt about why that's risky. Malicious JavaScript, from cross-site scripting (XSS) or a compromised dependency, runs with the same privileges as your own code. It can read `localStorage` and IndexedDB. It can also start a fresh OAuth flow in a hidden iframe and get a brand-new set of tokens, which short lifetimes, refresh-token rotation and even DPoP don't stop. An HttpOnly cookie doesn't make XSS harmless. The attacker's script can still send requests as the user, and the RFC says application-level measures can't prevent that. What the cookie does is stop them taking the credential away with them and using it later from somewhere else. The RFC also recommends against using JavaScript to write tokens into cookies, because they then get sent to your server on every request by accident. * * * ## Setup 1: server-side sessions This is the default for most web apps. The code below has three parts across the next sections. This first part is a session store and the cookie header. ```python """auth_demo.py - sessions, a strict JWT verifier and rotating refresh tokens. Standard library only. For production, use a maintained JWT library.""" import base64 import hashlib import hmac import json import secrets import time class InvalidToken(Exception): pass def _digest(value): """Store hashes, so a leaked table can't be replayed. Random 256-bit values don't need a slow hash.""" return hashlib.sha256(value.encode()).hexdigest() # ---------- 1. server-side sessions: an opaque id in a cookie ---------- class SessionStore: def __init__(self, idle=1800, absolute=28800, now=time.time): self.idle, self.absolute, self.now, self.rows = idle, absolute, now, {} def create(self, user_id): # call on login: always a NEW id, which defeats session fixation sid, t = secrets.token_urlsafe(32), self.now() # 256 bits from the OS CSPRNG self.rows[_digest(sid)] = {"user": user_id, "created": t, "seen": t} return sid def load(self, sid): key = _digest(sid or "") row = self.rows.get(key) if row is None: return None t = self.now() if t - row["seen"] > self.idle or t - row["created"] > self.absolute: del self.rows[key] return None row["seen"] = t return row["user"] def revoke(self, sid): # logout: takes effect on the very next request self.rows.pop(_digest(sid or ""), None) def revoke_all(self, user_id): # "log out everywhere", or after a password change self.rows = {k: r for k, r in self.rows.items() if r["user"] != user_id} def session_cookie(sid, max_age=None): cookie = f"__Host-sid={sid}; Path=/; Secure; HttpOnly; SameSite=Lax" return cookie + (f"; Max-Age={max_age}" if max_age else "") ``` A few details are worth knowing: - **The ID is 256 random bits from the operating system.** OWASP's minimum is 64 bits of entropy and it suggests at least 128 when you generate your own. - **Only hashes are stored.** If the table leaks, nobody can replay the IDs. A fast hash is fine for random 256-bit values, unlike for passwords. - **Login always creates a new ID.** That defeats session fixation, where an attacker plants an ID before the victim logs in. - **There are two timeouts.** The idle timeout resets on activity, and the absolute timeout doesn't. OWASP and MDN both describe them. - **Revoking is one delete,** and `revoke_all` covers password changes. ### The cookie ASVS asks for four things on a session cookie: `Secure`, `HttpOnly`, `SameSite` and the `__Host-` prefix. The prefix makes browsers reject the cookie unless it is `Secure`, has `Path=/` and has no `Domain`, so a sibling subdomain can't overwrite it. `SameSite=Lax` sends the cookie on top-level navigations, such as clicking a link in an email, so users arrive logged in. `Strict` only sends it from your own site, which RFC 10017 prefers for a BFF but which makes the first page of an inbound link load logged out. Choose `Strict` for sensitive apps. > **Heads up:** `SameSite` is only part of a CSRF defense. MDN says so, and RFC 10017 explains why: if another subdomain on your site is taken over, its requests count as same-site. Add a CSRF token or require a custom request header on state-changing requests. Newer is the `__Host-Http-` prefix, which RFC 10017 recommends. It also guarantees the cookie was set by a server header and not by script. MDN lists it, but check browser support before relying on it. `__Host-` is widely supported. * * * ## Setup 2: short-lived JWTs When many services or a mobile app need to verify who's calling, a signed token fits. This part signs and, more importantly, verifies one: ```python # ---------- 2. JWT access tokens: verify everything, trust nothing in the header ---------- def _b64e(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def _b64d(text): return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) def sign_jwt(claims, key, iss, aud, ttl=600, now=time.time): issued = int(now()) body = {**claims, "iss": iss, "aud": aud, "iat": issued, "exp": issued + ttl} parts = [_b64e(json.dumps(p, separators=(",", ":")).encode()) for p in ({"alg": "HS256", "typ": "JWT"}, body)] signing_input = ".".join(parts) return signing_input + "." + _b64e(hmac.new(key, signing_input.encode(), hashlib.sha256).digest()) def verify_jwt(token, key, iss, aud, leeway=30, now=time.time): if len(key) < 32: raise InvalidToken("key too short: use at least 32 random bytes") try: head_b64, body_b64, sig_b64 = token.split(".") header, claims, signature = json.loads(_b64d(head_b64)), json.loads(_b64d(body_b64)), _b64d(sig_b64) except ValueError: # wrong number of parts, bad base64 or bad JSON raise InvalidToken("malformed token") if not isinstance(header, dict) or not isinstance(claims, dict): raise InvalidToken("malformed token") if header.get("alg") != "HS256": # pin the algorithm. Never let the token choose raise InvalidToken("unexpected algorithm") expected = hmac.new(key, f"{head_b64}.{body_b64}".encode(), hashlib.sha256).digest() if not hmac.compare_digest(expected, signature): raise InvalidToken("bad signature") if claims.get("iss") != iss: raise InvalidToken("wrong issuer") audience = claims.get("aud") if aud not in (audience if isinstance(audience, list) else [audience]): raise InvalidToken("wrong audience") exp, nbf, t = claims.get("exp"), claims.get("nbf", 0), now() if not isinstance(exp, (int, float)) or t > exp + leeway: # a token with no expiry is never accepted raise InvalidToken("expired, or no exp claim") if not isinstance(nbf, (int, float)) or nbf > t + leeway: raise InvalidToken("not valid yet") return claims ``` Verification is where JWT systems get hurt. RFC 8725 lists the known failures, and the verifier above handles each: - **Pin the algorithm.** The token's header must never choose how it's verified. An attacker can set `alg` to `none`, or turn an RS256 token into an HS256 one and use the public key as the secret. This verifier accepts one algorithm and compares the string exactly. - **Check every claim:** issuer, audience and expiry. A token with no `exp` is refused. - **Use a strong key.** Weak HMAC secrets can be cracked offline from a captured token, so the verifier demands at least 32 random bytes. - **Compare signatures in constant time.** Here is every forged token from the tests, and how it fared: ```text forged token result alg set to none, no signature rejected: unexpected algorithm alg set to NoNe rejected: unexpected algorithm alg swapped to RS256 rejected: unexpected algorithm payload edited to sub=admin rejected: bad signature signed with the attacker's key rejected: bad signature expired token rejected: expired, or no exp claim token for a different audience rejected: wrong audience token with no expiry rejected: expired, or no exp claim ``` The tests also cover 12 malformed tokens, which must raise one clean error and nothing else, plus header-supplied keys, which are ignored. > **Heads up:** this example uses HS256 for brevity. If more than one service verifies your tokens, use asymmetric signatures such as RS256 or ES256, as OWASP's JWT cheat sheet explains. Verifiers then need only the public key and never hold a secret that could mint tokens. In production, use a maintained JWT library and apply the same checks. RFC 8725 is also being revised, so watch for the newer guidance. ### Refresh tokens Short access tokens need a way to renew without logging in again. That's the refresh token: opaque, hashed at rest, and rotated on every use. ```python # ---------- 3. refresh tokens: opaque, hashed, rotated on every use ---------- class RefreshStore: """Presenting an already-used token means someone has a copy, so the whole family is revoked.""" def __init__(self, lifetime=8 * 3600, now=time.time): self.lifetime, self.now, self.rows = lifetime, now, {} def issue(self, user_id, family=None, expires=None): token = secrets.token_urlsafe(32) self.rows[_digest(token)] = {"user": user_id, "family": family or secrets.token_hex(8), "expires": expires or self.now() + self.lifetime, "used": False} return token def rotate(self, token): row = self.rows.get(_digest(token or "")) if row is None: raise InvalidToken("unknown refresh token") if row["used"]: self.rows = {k: r for k, r in self.rows.items() if r["family"] != row["family"]} raise InvalidToken("reuse detected: every token in this family is revoked") if self.now() > row["expires"]: raise InvalidToken("refresh token expired") row["used"] = True # the new token keeps the ORIGINAL expiry, so rotation can never extend a session forever return row["user"], self.issue(row["user"], row["family"], row["expires"]) ``` RFC 10017 sets the rules this follows: rotate on every use, give refresh tokens a maximum lifetime, and never let a rotated token extend that lifetime. Its example is a 10-minute access token with an 8-hour refresh token. The tests confirm the original expiry holds across eight rotations in eight hours. If an old token comes back, someone has a copy, and the code revokes the whole family. The newest token dies too, so the real user has to log in again. That's the trade-off. > **Heads up:** rotation has a known gap, and the tests prove it. A thief who always grabs the newest token, while the real app stays offline or silent, is never detected: 20 rotations in a row, no alarm. RFC 10017 describes the same attack. In a browser, malicious script can do exactly that, which is why the RFC pushes browser apps toward a BFF instead. * * * ## Setup 3: a BFF for single-page apps A backend-for-frontend moves the OAuth work to your server. The server is the OAuth client and keeps the access and refresh tokens. The browser only gets a session cookie, exactly like Setup 1. RFC 10017 says this pattern withstands most XSS scenarios, because there are no tokens in the browser to steal, and a new OAuth flow started from the browser can't succeed: the server is a confidential client, so a stolen authorization code is useless without its credentials. The attacker can still send requests through the app as the user, but they can't walk away with the credential. The RFC's rules for the BFF: - The session cookie follows Setup 1's rules. `Secure` and `HttpOnly` are required, and `SameSite=Strict` and the `__Host-Http-` prefix are recommended. - CSRF protection is required. A custom request header plus a strict CORS policy works. - The BFF must only forward requests to an explicit allowlist of API hosts. Otherwise an attacker can aim it at their own server and collect users' tokens. The cost is a new component that proxies all API traffic. If your frontend and API share a domain and you don't need OAuth, skip it and use Setup 1. * * * ## Checklist - Default to server-side sessions for browser apps. - Use `__Host-`, `Secure`, `HttpOnly` and a deliberate `SameSite`, and add CSRF protection beyond it. - Create a new session ID at login, set idle and absolute timeouts, and revoke on logout and password change. - JWTs: short-lived, a pinned algorithm, issuer, audience and expiry checked, strong keys, and never in `localStorage`. - Refresh tokens: rotate on use, hash at rest, absolute lifetime, and revoke the family on reuse. - For sensitive single-page apps, use a BFF. Next in this series: how OAuth 2.0 and PKCE fit in, and what the login redirect is really doing.