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.
3 points to say:
- A BFF is best: the backend holds the tokens and JS never sees them.
- Cookie flags:
HttpOnly(JS can't read),Secure,SameSite=Lax(reduces CSRF), the__Host-prefix (host-only,Path=/). HttpOnlydoes 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.