CodePark/ questions / JWT in depth
START PRACTICINGPRACTICE
Backend question · Auth & security › JWT in depth

A SPA talks to its own backend on the same site. Which token storage gives the best protection against an XSS payload stealing the token?

An HttpOnly, Secure, SameSite cookie set by the backend, with CSRF defences in place

An HttpOnly cookie gives the best protection, because JavaScript can't read it. So an injected script can't copy the token and send it to the attacker. The script can still send requests from the page while it runs.

"
sessionStorage, because it is cleared when the tab closes" feels safer, but it isn't. Injected script can read sessionStorage just as easily as localStorage.

The cookie approach swaps the XSS risk for a CSRF risk.
CSRF (Cross-Site Request Forgery) means another site tricks the browser into sending a request with your cookie. SameSite cookies and CSRF tokens handle that risk.