Course contentsShow
← Web Development
Lesson 1599 of 2,98229. Web Authentication PatternsFree lesson

Token Storage in Single-Page Applications

Handle token persistence challenges in SPAs where page refreshes lose memory-stored tokens.

Token Storage in Single-Page Applications

You'll learn how to handle the unique challenge of storing authentication tokens in SPAs where every page refresh wipes in-memory state.

The SPA Token Persistence Problem

Single-Page Applications run entirely in the browser without traditional page reloads. This creates a dilemma: if you store tokens only in memory (JavaScript variables) for maximum security, they vanish the moment a user refreshes the page or closes a tab. Your users would be forced to log in again constantly—a terrible experience.

The Storage Trade-off

You face three options, each with compromises:

  1. localStorage/sessionStorage: Tokens survive refreshes but are vulnerable to XSS attacks (any malicious script can read them)
  2. HttpOnly cookies: Secure from XSS but require careful CSRF protection and backend coordination
  3. Memory-only with refresh tokens: Store short-lived access tokens in memory and longer-lived refresh tokens in HttpOnly cookies

A Common Pattern

Many SPAs adopt a hybrid approach:

  • Store a refresh token in an HttpOnly cookie (survives refresh, protected from XSS)
  • Keep the access token in memory (used for API calls)
  • On page load, if no access token exists in memory, automatically call a /refresh endpoint
  • The backend reads the HttpOnly cookie, validates it, and returns a new access token
  • Store that access token in memory for the session

This balances security and user experience: the sensitive access token stays in memory during active use, but users aren't logged out on refresh because the refresh token persists safely.

Key Takeaway: SPAs must balance token persistence with security—hybrid approaches using HttpOnly cookies for refresh tokens and memory storage for access tokens offer the best compromise between user experience and protection against XSS attacks.