← Back to Frontend, page 2

frontend-0034 · Hard senior

Where should a single-page app store an authentication token, and what can an attacker do in each case if there is an XSS bug?

A token in localStorage can be read and sent away by any script that runs in the page, so one XSS bug leaks it. A session in an HttpOnly cookie cannot be read by scripts, but the attacker's script can still make requests that carry it, and the cookie then needs CSRF protection. Neither option is safe against XSS, so prevention and short lifetimes matter most.

Full answer

The choice is a trade-off between two risks, XSS and CSRF.

Token in localStorage or sessionStorage, sent in an Authorization header:

  • Any script in the origin can read it, including injected scripts and compromised third-party libraries. After a single XSS bug the attacker can copy the token and use it from anywhere, for as long as it is valid.
  • It is not sent automatically, so there is no CSRF risk from this token.
  • Easy to use for APIs on other domains.

Session or token in an HttpOnly; Secure; SameSite cookie:

  • Scripts cannot read it, so it cannot be copied out of the browser by XSS.
  • The browser sends it automatically, so a forged cross-site request is possible. Use SameSite=Lax or Strict, a CSRF token or an Origin check.
  • With XSS the attacker's script can still call your API from the victim's browser, and the cookie goes along. The damage is limited to the time the victim has the page open, and the attacker cannot take the session home.

A balanced design that many teams use: a short-lived access token kept in memory, and a long-lived refresh token in an HttpOnly, Secure, SameSite cookie scoped to the refresh path. On page load the app asks the refresh endpoint for a new access token. Rotating refresh tokens and revoking them on reuse limits theft further. The backend-for-frontend pattern goes further, and keeps all tokens on a server that gives the browser only a session cookie.

Whichever way is chosen, reduce XSS: escape output, set a strict CSP, vet third-party scripts and use Subresource Integrity.

The test serves a page that sets an HttpOnly cookie and also stores a token in localStorage. A script that plays the attacker reads both. It gets the storage token but cannot see the cookie, yet a fetch call from the same page is still authenticated by the cookie.

javascript
import http from 'node:http';

const page = `<!doctype html><title>app</title><p>app</p>
<script>
  localStorage.setItem('token', 'abc123');
  // What injected script could do:
  window.stolen = { cookie: document.cookie, token: localStorage.getItem('token') };
  window.me = fetch('/me').then((r) => r.text());
</script>`;

http.createServer((req, res) => {
  if (req.url === '/me') {
    const ok = (req.headers.cookie ?? '').includes('session=s3cret');
    return res.end(ok ? 'user: asha' : 'anonymous');
  }
  res.setHeader('Set-Cookie', 'session=s3cret; HttpOnly; SameSite=Lax; Path=/');
  res.setHeader('Content-Type', 'text/html');
  res.end(page);
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The script that stands for injected code read the localStorage token, could not see the HttpOnly cookie in document.cookie, and a fetch from the page was still authenticated by the cookie.

Key points

  • localStorage tokens are readable by any script in the origin.
  • HttpOnly cookies cannot be read by scripts, but XSS can still make authenticated calls.
  • Cookies need SameSite and CSRF protection because they are sent automatically.
  • Short-lived memory access token plus an HttpOnly refresh cookie is a common design.
  • Preventing XSS matters in every design.

Common mistakes

  • Saying HttpOnly cookies make XSS harmless.
  • Saying localStorage is fine because the site has no XSS today.
  • Using long-lived access tokens with no rotation or revocation.
  • Forgetting the Secure flag and sending cookies over HTTP.

Follow-ups

  • What is the backend-for-frontend pattern?
  • How does refresh token rotation detect theft?
  • How would a strict CSP change the XSS risk?

Tips

  • Present it as a trade-off with a recommendation, not as a single right answer.
  • Name the in-memory token plus refresh cookie design.