SteelReed

Search

Search posts, questions…

SecurityQuestion 13 / 24

Middle

Where should a SPA store tokens, and which flags should a session cookie have?

Short answer

The safest option is keeping tokens out of JavaScript: use a BFF, and the browser only holds a session cookie HttpOnly; Secure; SameSite=Lax. If the SPA must hold tokens: access token in memory, refresh token in an HttpOnly cookie with a narrow Path; with localStorage any XSS can read it.

yesnoavoidCan you run a BFF?BFF holds tokensbrowser: session cookieAccess tokenin a JS variableRefresh token: HttpOnlycookiePath=/auth/refreshlocalStorageXSS reads it, long exposure

3 points to say:

  1. A BFF is best: the backend holds the tokens and JS never sees them.
  2. Cookie flags: HttpOnly (JS can't read), Secure, SameSite=Lax (reduces CSRF), the __Host- prefix (host-only, Path=/).
  3. HttpOnly does not stop XSS: the script can still send requests as the user, it just can't steal the cookie.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.