Security & Best Practices

JWT Token — Where to Store JWT in Browser?

JWT Token — Where to Store JWT in Browser?

What is a JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

JWTs can be signed using:

  • A secret (with HMAC algorithm)
  • A public/private key pair using RSA

Key Properties

Compact: Because of its size, it can be sent through a URL, POST parameter, or inside an HTTP header. Its small size means fast transmission.

Self-contained: The payload contains all the required information about the user, to avoid querying the database more than once.

Important Note on Security

JWT guarantees data ownership but not encryption. The JSON data stored in a JWT can be seen by anyone that intercepts the token, because it's just serialized — not encrypted. For this reason, always use HTTPS with JWTs.

JWT is particularly useful for API authentication and server-to-server authorization.

Where to Store JWT in the Browser?

A JWT needs to be stored in a safe place inside the user's browser. The answer is clear:

❌ Never Store JWT in localStorage or sessionStorage

If you store it inside localStorage, it's accessible by any script inside your page. An XSS attack could give an external attacker access to the token. Any third-party scripts you include — if compromised — can access all your users' tokens.

✅ Always Store JWT in an httpOnly Cookie

An httpOnly cookie is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.

// Setting an httpOnly cookie on the server (Node.js example)

res.cookie('token', jwtToken, { httpOnly: true, // Not accessible via JavaScript secure: true, // Only sent over HTTPS sameSite: 'strict', // CSRF protection maxAge: 24 60 60 1000 // 24 hours });

This protects against XSS attacks — even if an attacker injects malicious JavaScript into your page, they cannot read the JWT from the httpOnly cookie.

Summary

StorageXSS SafeAccessible via JSRecommendation
localStorage❌ No✅ YesNever use
sessionStorage❌ No✅ YesNever use
httpOnly Cookie✅ Yes❌ NoAlways use

Originally published on LinkedIn*

JWTSecurityAuthenticationJavaScriptWebSecurityNodeJS
Available for new opportunities

Have a system that needs an architect?

I'm open to full-time roles, contract engagements and product/architecture work. Everything on this site is a system I designed, built, deployed and still operate — the next one could be yours.

“Give me a problem. I'll architect it, build it, and ship it.”

— Deepak Kumar Jha