The XSS Problem

Cross-site scripting lets attackers run JavaScript in your origin. localStorage is fully readable by scripts — one XSS equals full account takeover.

Secure Alternatives

  • httpOnly Secure SameSite cookies — best for traditional web
  • Memory only — SPAs that accept re-login on refresh
  • BFF pattern — backend holds tokens, frontend gets session cookie

CSP Helps But Is Not Enough

Content-Security-Policy reduces XSS risk but misconfigurations happen. Defense in depth: httpOnly + CSP + input sanitization.

Mobile

Use Keychain (iOS) and Keystore (Android) — never plain SharedPreferences for tokens.

Understanding Why Storing JWT in localStorage Is Dangerous in Production

Developers search for Why Storing JWT in localStorage Is Dangerous when building API authentication with JSON Web Tokens. JWTs are used by OAuth 2.0, OpenID Connect, Auth0, Firebase, AWS Cognito, and Keycloak. Always validate exp, iss, and aud server-side — decoding alone proves nothing about authenticity.

JWT Structure Recap

Every JWT has three dot-separated segments: header (algorithm), payload (claims), signature (proof). Use JWT Decoder to inspect and JWT Validator to verify before trusting any claim value in production code.

Common Pitfalls

  • Algorithm confusion (none attack) — whitelist allowed algorithms
  • Secrets in the payload — payload is only Base64-encoded, not encrypted
  • Ignoring clock skew on exp and nbf
  • Weak HMAC secrets — use 256-bit random keys
  • Skipping signature verification — always call verify(), not decode()
  • Storing tokens in localStorage — XSS can steal them

Further Reading

Browse related resources: JWT Decoder, JWT Validator, JWT Basics, JWT Authentication, JWT Errors, Algorithms, Glossary, and Learning Path.

Try It Now

FAQ

Is localStorage safe for JWT?

No. Any XSS vulnerability exposes all tokens in localStorage. httpOnly cookies are not accessible to JavaScript.

What about sessionStorage?

Same XSS risk as localStorage. Not a security improvement.