Course contentsShow
← Web Development
Lesson 2922 of 2,98252. Frontend SecurityFree lesson

In-Memory Token Storage Pattern

Implement token storage in JavaScript memory variables to prevent persistence-based attacks.

In-Memory Token Storage Pattern

What you'll learn: How to store authentication tokens in JavaScript memory variables to eliminate persistence-based attack vectors.

The Core Idea

The in-memory token storage pattern keeps your authentication tokens (like JWTs) in plain JavaScript variables rather than persisting them to localStorage, sessionStorage, or cookies. When the token lives only in memory, XSS attackers can't steal it from browser storage, and the token automatically disappears when the user closes the tab or refreshes the page.

Think of it like keeping your house key in your pocket versus leaving it under the doormat. The pocket (memory) is only accessible while you're present, but the doormat (persistent storage) remains there for anyone who knows where to look.

How It Works

You store tokens in a closure or module-scoped variable:

// token-manager.js
let authToken = null;

export function setToken(token) {
  authToken = token;
}

export function getToken() {
  return authToken;
}

export function clearToken() {
  authToken = null;
}

When making authenticated requests:

import { getToken } from './token-manager.js';

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

The Tradeoff

The downside? Your users must log in again after every page refresh. This makes in-memory storage most suitable for highly sensitive applications where security outweighs convenience, or when paired with a secure refresh token mechanism using HttpOnly cookies.

Key Takeaway: In-memory token storage provides the strongest XSS protection by keeping tokens in JavaScript variables that vanish on page reload, though it requires re-authentication on every session.