Which Browser Storage Is Best for JWT? Cookie vs localStorage vs sessionStorage

This article compares three browser storage options for JWT—Cookie, localStorage, and sessionStorage—examining how each works, their automatic handling, and security implications such as CSRF and XSS, ultimately recommending Cookies with proper SameSite and HttpOnly settings for stronger protection.

Programmer DD
Programmer DD
Programmer DD
Which Browser Storage Is Best for JWT? Cookie vs localStorage vs sessionStorage

In recent years I have used JWT as an authentication token. I have a question: where should the server‑issued JWT be stored in the browser? In this browser scenario there are three options.

Cookie

The server can send the JWT to the browser via a Cookie; the browser automatically includes the JWT in the Cookie header on subsequent requests, and the server validates it. However, this approach is vulnerable to CSRF attacks.

The mitigation is to set the Cookie’s SameSite attribute to Strict, so the Cookie is only sent when the request origin matches the target URL.

Cookies are also vulnerable to XSS attacks because JavaScript can read them. To prevent this, set the Cookie’s HttpOnly attribute.

response.setHeader("Set-Cookie","jwt=jwt_value;Path=/;Domain=domainvalue;Max-Age=seconds;HttpOnly")
You can set the token’s lifetime with the Max-Age attribute.

localStorage

localStorage can also store the JWT. This method is not susceptible to CSRF, but the token is not sent automatically with requests; you must add it manually in code. It is vulnerable to XSS, and the token persists until the user clears it.

sessionStorage

sessionStorage is similar to localStorage, but its lifetime is limited to the browsing session; the data is cleared when the page or browser is closed.

Summary

All three methods share the same drawback—susceptibility to XSS attacks. Pay special attention to XSS protection and follow best practices.

Conclusion

Because all three approaches are vulnerable to XSS, high‑security applications should configure defenses carefully. Among them, Cookies offer many security options such as SameSite and HttpOnly, making them the preferred choice.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CSRFXSSJWTCookielocalStoragesessionStorage
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.