JWT in localStorage vs httpOnly cookie — which is safer?
poze 5 months ago566 gadeen
For my SPA's authentication, tutorials disagree: some store the JWT in localStorage, others in a cookie. What's the actual security difference?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
2 Repons
- 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.
Konekte pou di lòt moun si li te mache.
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.
Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.