JWT in localStorage vs httpOnly cookie — which is safer?

asked 5 months ago570 viewsen

3

For my SPA's authentication, tutorials disagree: some store the JWT in localStorage, others in a cookie. What's the actual security difference?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

2 Answers

9
✓
✓ Accepted answer

- localStorage: any JavaScript on your page can read it, so a single XSS bug (or a compromised npm dependency) lets an attacker steal the token and use it from anywhere until it expires. - httpOnly cookie: JavaScript can't read it. XSS can still make requests *from the victim's browser*, but it can't exfiltrate a long-lived credential. You must handle CSRF, which is largely addressed by SameSite=Lax (or Strict) plus checking Origin on state-changing requests.

Recommended for a browser app served from your own domain:

Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=...

Notes: - For a first-party web app, a plain server-side session cookie is often simpler than JWT and easier to revoke. - JWTs are handy for service-to-service calls and mobile clients (stored in secure storage). - Whatever you choose: short expiry, server-side revocation for "log out everywhere", and a strict Content Security Policy to reduce XSS risk in the first place.

Sign in to tell others whether this worked.

answered 5 months ago
5

One nuance: if your API is on a different *site* than your frontend (not just a different subdomain), SameSite cookies get more complicated and third-party cookie restrictions apply. Serving the API under the same site (api.example.com for app.example.com) keeps cookies simple.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.