EasyAuthentication📖 Theory Question

What are the security differences between storing a JWT in localStorage vs an HttpOnly cookie?

💡

Hint

localStorage is XSS-vulnerable; HttpOnly cookies are inaccessible to JS but need CSRF protection

Full Answer

localStorage

  • Accessible via JavaScript — any XSS vulnerability can steal the token: document.cookie — wait, actually localStorage.getItem('token').
  • Token theft = account takeover. Attacker can make authenticated API calls from anywhere.
  • Not automatically sent to the server — must manually attach: Authorization: Bearer <token>.

HttpOnly cookie

  • HttpOnly flag prevents JavaScript from reading the cookie — XSS cannot steal it.
  • Secure flag ensures it only travels over HTTPS.
  • SameSite=Strict/Lax prevents CSRF — cookie not sent on cross-origin requests.
  • Automatically included by the browser on every same-origin request — no manual header attachment.
Set-Cookie: token=<jwt>; HttpOnly; Secure; SameSite=Strict; Path=/

Verdict: HttpOnly cookies are strictly more secure. The main downside is CSRF risk (mitigated by SameSite) and that the token is sent on every request (including non-API routes) — use a short Path to scope it.

More Authentication Questions

EasyWhat is refresh token rotation and why is it important?EasyWhat is OAuth 2.0 PKCE and when should you use it?EasyWhat is the difference between authentication and authorization?EasyWhat is SSO (Single Sign-On) and how is it implemented on the frontend?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint