Why is storing JWTs in localStorage dangerous?
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
Token storage is where authentication design meets XSS, and interviewers use it to see whether you understand JWTs as bearer credentials rather than magic strings. The strongest answers separate what the token is (signed claims), what it represents (possession equals identity), and where it lives (JavaScript-readable storage versus HttpOnly cookies), then name the trade-off each choice creates. The question also opens the door to refresh rotation and revocation, which is where senior candidates stand out.
Mental model
A JWT is a signed, base64url-encoded claim set and a bearer credential: whoever holds the string is treated as the user. localStorage is readable by every script on the origin, so any XSS turns a stored token into silent, valid-until-expiry account takeover. HttpOnly cookies move the credential out of JavaScript reach and have the browser attach it automatically, trading XSS exfiltration for CSRF exposure that SameSite and CSRF tokens must then handle.
Step-by-step solution
Step 1: Three parts, no secrets
A JWT is three base64url segments joined by dots: a header describing the algorithm, a claims payload, and a signature. Base64url is reversible encoding, not encryption, which is the first misconception this question tests. Anyone holding the token can decode the payload and read every claim — user id, role, expiry — and the animation shows exactly that, with the decoded object appearing beside the raw string. What the signature actually buys is integrity: it proves the server issued these claims and that nobody altered them, because forging a valid signature without the key is infeasible — provided the verifier pins the expected algorithm and rejects none; naive verification that trusts the token's own alg header falls to alg-confusion or unsigned-token attacks. It does not encrypt the payload and it does not identify the current holder. The distinction to say out loud in an interview is "signed, not secret" — then explain what that means for storage and trust.
javascript// raw token: header.payload.signature // eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1XzQ4MiIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc2MDAwMDAwMH0.9xQ... // decoded payload (anyone can do this) JSON.parse(atob('eyJzdWIiOiJ1XzQ4MiIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc2MDAwMDAwMH0')) // { "sub": "u_482", "role": "admin", "exp": 1760000000 }Step 2: A bearer token is a key
The word bearer is literal: whoever bears the token gets the access. The server validates the signature and the expiry claim, then trusts the identity inside — it has no way to know whether the request came from the human who logged in or from someone who copied the string. There is no device binding and no session identifier the server can revoke unless you built one. The animation walks through this asymmetry: a thief who obtains the token replays one request and the server treats it as a perfectly valid session, because cryptographically it is one. Two consequences follow. First, guard the token with the same care as a password, especially against XSS. Second, if you need revocation, add server-side state such as a token id denylist or short expiries with rotation, because a stateless JWT cannot be un-issued.
Step 3: localStorage versus HttpOnly cookies
This is the heart of the question. localStorage is readable by any JavaScript running on the origin, including a payload planted by a single XSS flaw anywhere on the site. The animation's left pipeline shows the theft end to end: the app stores the access token with localStorage.setItem, an injected script calls getItem, and one outbound fetch sends it to the attacker — no user interaction, no visible trace, and the token remains valid until exp. The right pipeline uses an HttpOnly, Secure, SameSite cookie: the browser stores the credential outside the JavaScript-accessible cookie API, attaches it automatically on requests to the origin, and document.cookie returns an empty string. XSS can still act through the victim's browser, but it cannot walk away with a long-lived credential. That is the trade the next step expands on.
javascript// localStorage: readable by ANY script on the origin localStorage.setItem('access_token', token); const stolen = localStorage.getItem('access_token'); // XSS does this // HttpOnly cookie: out of JavaScript reach // Set-Cookie: access_token=...; HttpOnly; Secure; SameSite=Lax document.cookie; // '' — the token is not hereStep 4: Cookies trade XSS for CSRF
Moving a token from localStorage into a cookie fixes exfiltration by JavaScript but reintroduces a classic problem: browsers attach cookies automatically based on destination, so another site can cause the victim browser to send authenticated requests. That is CSRF. The mitigation set is well understood — mark cookies Secure so they never travel over plain HTTP, set SameSite=Lax or Strict so cross-site requests do not carry them, and validate an anti-CSRF token on state-changing endpoints. The animation shows the trade directly. On the left, script reads a localStorage token and exfiltrates it; on the right, the cookie never appears in JavaScript, but the browser will volunteer it to bank.com from any tab, which is the exposure you now own. Prefer cookies plus CSRF defenses; the alternative keeps long-lived tokens exactly where a single XSS can steal them.
Step 5: Short-lived tokens, rotating refresh
No storage choice removes the need to limit damage. Long-lived access tokens are the worst case: a stolen token stays valuable until its exp, which may be days away. The standard pattern pairs a short-lived access token — roughly five to fifteen minutes — with a refresh token stored in an HttpOnly cookie. When the access token expires, the client calls the refresh endpoint for a new one. Rotation means each refresh issues a new refresh token and invalidates the old one; if an old token is presented twice, the server treats it as theft and revokes the whole session family. The animation contrasts a single month-long token that keeps working after theft with a rotating pair that turns the same theft into a short window and a detectable event. Add a jti denylist or a token version claim when you need immediate revocation on logout.
Edge cases & traps
- Keeping tokens in memory only: it reduces XSS exposure but loses sessions on refresh — pair it with an HttpOnly refresh cookie or accept re-login.
- Using sessionStorage as a safer localStorage: any script on the origin still reads it for the tab's lifetime, so XSS exfiltrates just as easily.
- Long-lived access tokens in cookies: HttpOnly stops JavaScript theft, but a leaked cookie stays valid for its full lifetime — keep exp short and rotate.
- Refresh rotation without reuse detection: a stolen refresh token can be used forever — detect replay and revoke the entire token family.
- Stateless JWTs with no revocation path: logout and password changes cannot un-issue them — add a jti denylist, a token version claim, or both.