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
| Storage | XSS Safe | Accessible via JS | Recommendation | |---|---|---|---| | localStorage | ❌ No | ✅ Yes | Never use | | sessionStorage | ❌ No | ✅ Yes | Never use | | httpOnly Cookie | ✅ Yes | ❌ No | Always use |
Originally published on LinkedIn*
