Skip to the page

Authentication in the frontend · senior

Where to keep sessions and tokens: cookie, memory, localStorage, BFF

There is no perfect place: localStorage is readable by any XSS, in-memory tokens are lost on reload, HttpOnly cookies hide the token from JS but need CSRF defences, and the Backend-for-Frontend pattern (recommended for sensitive apps by RFC 10017, 2026) keeps tokens on the server entirely.

The notes

What you must know

  • localStorage/sessionStorage: any script on the page (XSS, a compromised npm package, a third-party tag) can read and exfiltrate the token and use it from anywhere until it expires.
  • HttpOnly + Secure + SameSite cookie: JS cannot read it; the browser sends it automatically, so you need CSRF defences. XSS can still make requests while the user is on the page.
  • In-memory access token (a JS variable) + refresh token in an HttpOnly cookie: short-lived access token (5 to 15 min), silent refresh on load or on 401. Handle many tabs and concurrent 401s with a single refresh.
  • BFF (Backend for Frontend): the browser has only a session cookie with a same-origin backend; the backend holds OAuth tokens and calls APIs. RFC 10017 (OAuth 2.0 for Browser-Based Applications, Aug 2026) recommends it for business and sensitive apps.
  • Refresh tokens in the browser must be rotated on every use (or sender-constrained, e.g. DPoP) with a maximum lifetime; reuse of an old refresh token should revoke the family.
  • Logout: clear client state, revoke refresh tokens server-side, and expire the cookie. On React Native use Keychain/Keystore (secure storage), never AsyncStorage.

The red pen

Common traps: mistake → fix

  • Mistake: "Store the JWT in localStorage, it's standard"

    Fix: any XSS or malicious dependency can steal it and use it from another machine.

  • Mistake: "HttpOnly cookies make XSS harmless"

    Fix: the attacker can't steal the cookie but can still act as the user from the page.

  • Mistake: "JWTs can't be revoked so just make them long-lived"

    Fix: keep access tokens short and revoke refresh tokens on the server.

  • Mistake: "Cookies are always vulnerable to CSRF"

    Fix: with SameSite, CSRF tokens or Fetch Metadata checks they are well protected.

Easy to hard

Questions interviewers ask, easy to hard

  1. Where should a SPA store its access token and refresh token? Defend your choice.
  2. What attacks does each option protect against, and which does it not?
  3. How does silent refresh work, and how do you avoid five parallel refresh calls?
  4. What is the BFF pattern and when is it worth the extra server?
  5. How do you log a user out of all devices?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview