HeadlinesBriefing favicon HeadlinesBriefing.com

JWT Token Storage: localStorage vs httpOnly Cookies

Hacker News •
×

The article examines three approaches to storing JWTs in frontend applications, each with distinct security tradeoffs. Storing tokens in localStorage remains common in tutorials but exposes them to any JavaScript running on the page — including compromised npm packages, analytics scripts, or injected XSS payloads. An attacker who executes code can exfiltrate the token with a single `fetch` call and reuse it from their own infrastructure until expiry, effectively bypassing server-side revocation since JWTs are stateless by design.

Holding the access token in a memory variable narrows the attack surface — the token isn't enumerable like localStorage — but introduces usability failures: page refreshes or new tabs log users out. Adding a refresh token to persist sessions merely shifts the problem; if that refresh token lives in localStorage, attackers gain indefinite minting capability. The author argues JavaScript-reachable storage cannot safely hold long-lived credentials.

The recommended pattern uses an httpOnly cookie with `Secure`, `SameSite=Lax`, and `Path=/` flags. The browser automatically attaches it to requests while denying JavaScript access entirely. During XSS, attackers can only ride the live session from the victim's tab — requests hit your rate limits and logging — rather than stealing a portable bearer token. This reduces blast radius without sacrificing persistence across refreshes or tabs.