JWT storage: localStorage versus httpOnly cookies
client-side token storage threats.
localStorage is readable by JS so XSS can steal the token but no CSRF; httpOnly cookies block XSS theft but are auto-sent, enabling CSRF unless mitigated.
WHAT THIS TESTS Whether you understand that each storage location trades one attack vector for another and that neither is secure by default.
A GOOD ANSWER COVERS localStorage is accessible to any JavaScript running on the page. If an attacker injects script through an XSS vulnerability, they can read the token and send it anywhere, so localStorage maximizes XSS impact. However, the application must attach the token manually (for example in an Authorization header), and the browser never sends it automatically, so localStorage is not vulnerable to CSRF. An httpOnly cookie cannot be read by JavaScript, so even with an XSS flaw the attacker cannot directly exfiltrate the token, reducing XSS token theft. The catch is that browsers send cookies automatically on every matching request, which opens CSRF: a malicious site can trigger an authenticated request. You mitigate that with SameSite (Lax or Strict), a synchronizer or double-submit CSRF token, and Secure plus httpOnly flags.
COMMON WRONG ANSWERS Claiming httpOnly cookies are fully safe and need no further work, forgetting CSRF entirely, or thinking localStorage is safe because the token is just a string.
LIKELY FOLLOW-UPS What SameSite does and its limits, double-submit cookies, why XSS undermines almost any client storage, and how CSP reduces XSS risk.
ONE CONCRETE EXAMPLE If your SPA keeps the JWT in localStorage and a third-party script is compromised, that script reads localStorage and steals every user's token. Switching to an httpOnly, Secure, SameSite=Strict cookie blocks that theft, but you must add a CSRF token to state-changing requests so a forged cross-site POST cannot ride the automatically sent cookie.
Read the original → cheatsheetseries.owasp.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.