Where Should You Store JWT in the Browser? Cookie vs localStorage vs sessionStorage
This article compares three browser storage options for JWT—Cookie, localStorage, and sessionStorage—examining their automatic transmission, CSRF and XSS vulnerabilities, and security configurations such as SameSite and HttpOnly to help developers choose the safest method.
In recent projects I have used JWT as an authentication token and often wonder where the server‑issued JWT should be stored in the browser. In a browser‑only scenario there are three choices.
Cookie
The server can send the JWT via a Cookie; the browser automatically includes the Cookie in subsequent requests, and the server validates the token. However, this approach is vulnerable to CSRF attacks.
To mitigate CSRF, set the Cookie's
SameSiteattribute to
Strict, which prevents the Cookie from being sent on cross‑site requests.
Cookies are also exposed to XSS attacks, as malicious JavaScript can read them. Setting the
HttpOnlyattribute prevents client‑side scripts from accessing the Cookie.
<code>response.setHeader("Set-Cookie","jwt=jwt_value;Path=/;Domain=domainvalue;Max-Age=seconds;HttpOnly");</code>You can control the token's lifetime by setting the Max-Age attribute.
localStorage
localStorage can also hold the JWT. It is not susceptible to CSRF because the token is not sent automatically, but the application must add it to requests manually. This method is vulnerable to XSS, and the token persists in localStorage until the user explicitly clears it.
sessionStorage
sessionStorage behaves similarly to localStorage, but its lifecycle is limited to the browsing session; the data is cleared when the page or browser is closed.
Summary
All three methods share the same major drawback—susceptibility to XSS attacks. Developers should pay special attention to XSS protection and follow best practices.
Conclusion
Because all three storage options can be attacked via XSS, high‑security applications should apply targeted configurations. Cookies provide a range of security options such as
SameSiteand
HttpOnly, making them the preferred choice for storing JWTs.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.