advancedJWT: Token-Based Authentication
What's the security risk of storing a JWT in browser localStorage versus an HttpOnly cookie?
localStorage is accessible to any JavaScript running on the page, including malicious scripts injected via an XSS vulnerability — making token theft straightforward if XSS exists anywhere on the site. An HttpOnly cookie can't be read by JavaScript at all, mitigating XSS-based theft, but re-introduces CSRF risk (since browsers auto-attach cookies), which must then be mitigated with CSRF tokens or SameSite cookie attributes.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response