Where to Store JWTs: localStorage vs sessionStorage
You'll learn how to choose between browser storage options for JWTs and understand the persistence and security trade-offs of each.
When you receive a JWT from a server, you need somewhere safe to store it in the browser so you can include it in subsequent requests. The two most common choices are localStorage and sessionStorage, each with distinct characteristics.
localStorage: Persistent Storage
localStorage keeps your JWT even after the user closes their browser tab or restarts their computer. Think of it like saving a file to your hard drive—it persists until explicitly deleted.
Pros:
- Survives page refreshes and browser restarts
- Better user experience (users stay logged in)
Cons:
- Longer-lived tokens create a larger attack window
- If an attacker steals the token, it remains valid longer
sessionStorage: Tab-Scoped Storage
sessionStorage only lasts for the current browser tab's lifetime. Close the tab, and the JWT disappears. It's like writing on a whiteboard that gets erased when you leave the room.
Pros:
- Automatically cleared when the tab closes
- Reduced risk from forgotten logout
- More secure for shared or public computers
Cons:
- Users lose their session if they accidentally close the tab
- Each new tab requires re-authentication
- Poorer user experience for typical use cases
The Security Reality
Both options are vulnerable to XSS (Cross-Site Scripting) attacks—if malicious JavaScript runs on your page, it can read either storage type. Neither is inherently "more secure" against XSS. The difference is how long a compromised token remains valid.
Key Takeaway: Use sessionStorage for high-security scenarios (banking, admin panels) where inconvenience is acceptable, and localStorage for standard applications where user convenience matters more—but always pair with short JWT expiration times and implement proper XSS protection.