localStorage vs sessionStorage vs Cookies in JavaScript

Browsers give JavaScript three main ways to persist data client-side, each with different lifetimes and visibility — mixing them up leads to data disappearing (or not disappearing) when you expect the opposite.

// localStorage: persists indefinitely, until explicitly cleared
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme');
localStorage.removeItem('theme');

// sessionStorage: cleared when the TAB closes, isolated per tab
sessionStorage.setItem('formDraft', JSON.stringify({ name: 'Alice' }));

// Cookies: the only one automatically sent with every HTTP request
document.cookie = 'sessionId=abc123; max-age=3600; SameSite=Strict';

Choosing the Right One

  • localStorage — user preferences, theme settings, anything that should survive across sessions and tabs
  • sessionStorage — form drafts, wizard progress, anything scoped to one browsing session in one tab
  • Cookies — the only option if the server needs to read the value on every request (auth tokens, session IDs)

None of these are appropriate for sensitive data without additional protection — localStorage and sessionStorage are both readable by any JavaScript running on the page, making them vulnerable to XSS in a way an httpOnly cookie is not.