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

Memory Storage Patterns

Storing tokens only in JavaScript memory to prevent XSS theft, and handling page refreshes.

Memory Storage Patterns

You'll learn how to store authentication tokens exclusively in JavaScript memory to maximize security and handle the tradeoffs involved.

The Core Idea

Memory storage means keeping your JWT or authentication token in a plain JavaScript variable (like a module-level variable or React state) instead of localStorage, sessionStorage, or cookies. Because the token only exists in RAM during the current page session, it's invisible to XSS attacks that try to read storage APIs.

Think of it like keeping cash in your hand versus in your wallet. Someone can't pickpocket what you're actively holding—but if you set it down (page refresh), it's gone.

How It Works

You store the token in memory after login:

// Module-level variable
let authToken = null;

async function login(credentials) {
  const response = await fetch('/api/login', {
    method: 'POST',
    body: JSON.stringify(credentials)
  });
  const data = await response.json();
  authToken = data.token; // Stored only in memory
}

function getAuthToken() {
  return authToken;
}

Now when you make authenticated requests, you retrieve it from memory:

async function fetchUserData() {
  const token = getAuthToken();
  const response = await fetch('/api/user', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  return response.json();
}

The Page Refresh Problem

The major downside: when the user refreshes the page, the token vanishes. You must re-authenticate or implement a refresh token strategy using HTTP-only cookies to silently obtain a new access token on page load.

Key Takeaway: Memory storage provides the strongest XSS protection by keeping tokens out of browser storage entirely, but requires additional infrastructure to handle page refreshes gracefully.