CodePark/ questions / Cookies & browser storage
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Cookies & browser storage

Where should a browser app store authentication tokens, and why?

Store tokens in an HttpOnly, Secure, SameSite cookie, or keep a short-lived token in memory. Avoid localStorage and sessionStorage.

Why not Web Storage? Any JavaScript on the page can read localStorage or sessionStorage. So one XSS bug lets an attacker steal the token and use it from anywhere. XSS (cross-site scripting) means an attacker's script runs in your page.

Why cookies are safer:

  • HttpOnly: JavaScript cannot read the cookie.
  • Secure: the browser only sends it over HTTPS.
  • SameSite=Lax or Strict: this blocks most CSRF.

CSRF (cross-site request forgery) means another site makes the user's browser send a request to your site. Cookies bring this risk, because the browser sends them automatically. So add CSRF tokens for state-changing requests where SameSite is not enough.

A common pattern for token-based APIs: keep a short-lived access token in memory (a JavaScript variable). Keep a refresh token in an HttpOnly cookie.

No storage replaces preventing XSS. XSS can still make requests while the user is on the page. But HttpOnly stops the token from being stolen and sent to the attacker.

  • Any script can read Web Storage, so an XSS bug can steal tokens stored there.
  • Cookies with HttpOnly, Secure and SameSite are safer.
  • Cookies need CSRF protection, because the browser sends them automatically.
  • A common pattern is an in-memory access token plus an HttpOnly refresh cookie.
  • Nothing replaces preventing XSS.