Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

localStorage vs sessionStorage vs Cookies vs IndexedDB: Differences and Use Cases

Browser storage is not a single interchangeable resource. A theme preference, a form in progress, a session identifier and an offline document database have different requirements. The right choice depends on access scope, lifetime, security and data structure. These examples also handle unavailable storage and failed writes rather than assuming that browser data will always survive.

Published Written by Reading time 10 min read
On this page Contents: quick navigation between sections

Core differences: scope, lifetime and format

MechanismAccess scopeLifetimeDataTypical use
localStorageOriginAcross visitsTextPreferences
sessionStorageOrigin and tabTab sessionTextForm step
CookiesHost, Domain, PathSession or expiryTextHTTP session
IndexedDBOriginAcross visitsObjects, BlobOffline documents

Web Storage consists of localStorage and sessionStorage. Both store string key-value pairs through synchronous APIs. IndexedDB supports structured objects, Blob values, indexes and transactions. Cookies store small text values associated with HTTP. [1][5][8]

An origin combines scheme, host and port: https://app.example.com and https://admin.example.com have separate Web Storage and IndexedDB. Cookies instead follow host or Domain and Path rules plus security restrictions. [4][5]

localStorage: preferences across visits

const THEME_KEY = "app:theme:v1";

function isTheme(value) {
  return value === "light" || value === "dark";
}

function readTheme() {
  try {
    const value = localStorage.getItem(THEME_KEY);

    return isTheme(value) ? value : "light";
  } catch {
    return "light";
  }
}

function saveTheme(theme) {
  if (!isTheme(theme)) {
    return false;
  }

  try {
    localStorage.setItem(THEME_KEY, theme);

    return true;
  } catch {
    return false;
  }
}

saveTheme("dark");
console.log(readTheme());

Theme, table density and filter preferences can survive a reload and a browser restart. localStorage has no built-in TTL, but it is not permanent: users can clear it and browsers can restrict access. [1][3]

The example accepts only supported theme values and catches read and write failures. The app still works with a default when storage is unavailable. Large JSON objects require synchronous serialization and parsing; writing on every keystroke can delay work on the main thread. [1]

sessionStorage: forms and per-tab state

const STEP_KEY = "checkout:step:v1";

function readStep() {
  try {
    const step = Number(sessionStorage.getItem(STEP_KEY));

    return Number.isInteger(step) && step >= 1 && step <= 3 ? step : 1;
  } catch {
    return 1;
  }
}

function saveStep(step) {
  if (!Number.isInteger(step) || step < 1 || step > 3) {
    return false;
  }

  try {
    sessionStorage.setItem(STEP_KEY, String(step));

    return true;
  } catch {
    return false;
  }
}

saveStep(2);
console.log(readStep());

sessionStorage is scoped to the origin and top-level browsing context, typically a tab. It survives reloads but ordinarily ends with the tab session; browser session restoration can restore it. A new window with an opener may receive an initial copy, after which changes remain independent. [2]

For a multi-step form, save the current step rather than passwords or payment details. This example validates the step range and handles inaccessible storage. Multiple forms in one tab need separate keys. Open independent windows with noopener to avoid copying their initial state.

Cookies: HTTP state and authentication

Set-Cookie: __Host-session=REPLACE_WITH_RANDOM_ID; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800

The server sets cookies with Set-Cookie. Browsers attach matching cookies according to host, path, SameSite, credentials settings and privacy policies. Unlike Web Storage, this does not require manually copying a session ID into an Authorization header. Unnecessary cookies add request overhead. [5]

The response header below illustrates a server-generated random session identifier (placeholder value). Secure requires a secure connection, HttpOnly prevents JavaScript from reading the cookie, and SameSite=Lax restricts some cross-site requests. The __Host- prefix requires Secure, Path=/ and no Domain. Max-Age is in seconds, but the server must independently enforce session expiry and revocation. [5][6]

IndexedDB: an offline database

function openNotes() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("notes-demo", 1);

    request.onupgradeneeded = () => {
      const store = request.result.createObjectStore("notes", {
        keyPath: "id",
      });

      store.createIndex("updatedAt", "updatedAt");
    };

    request.onblocked = () => console.warn("Close other tabs to upgrade");
    request.onerror = () => reject(request.error);

    request.onsuccess = () => {
      const db = request.result;
      db.onversionchange = () => db.close();

      resolve(db);
    };
  });
}

function saveNote(db, note) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", "readwrite");

    tx.oncomplete = () => resolve();
    tx.onabort = () => reject(tx.error ?? new Error("Write aborted"));

    tx.objectStore("notes").put(note);
  });
}

function recentNotes(db, since) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", "readonly");
    const request = tx
      .objectStore("notes")
      .index("updatedAt")
      .getAll(IDBKeyRange.lowerBound(since), 50);

    tx.oncomplete = () => resolve(request.result);
    tx.onabort = () => reject(tx.error ?? new Error("Read aborted"));
  });
}

async function demoNotes() {
  const db = await openNotes();

  try {
    await saveNote(db, {
      id: "n1",
      text: "Draft",
      updatedAt: Date.now(),
    });

    return await recentNotes(db, Date.now() - 86400000);
  } finally {
    db.close();
  }
}

demoNotes().then(console.log).catch(console.error);

IndexedDB supports keyed records, indexes and atomic operations within transactions. The example creates a notes store with id as its key and updatedAt as an index. Schema changes occur in onupgradeneeded when the version increases. Other tabs can block an upgrade, so close the connection on versionchange. [8]

Treat a write as successful only after the transaction's complete event, not after a single put request succeeds. The index query retrieves records from a given date; a sample limit of 50 avoids reading an entire large collection. Do not await a network request inside an active transaction: the transaction may finish automatically. [8][9]

Quotas, eviction and performance

async function storageStatus() {
  const manager = navigator.storage;

  if (!manager?.estimate) {
    return null;
  }

  const { usage, quota } = await manager.estimate();

  return {
    usage,
    quota,
    persistent: manager.persisted ? await manager.persisted() : null,
  };
}

// Call from an explicit save-offline action.
async function requestPersistence() {
  return navigator.storage?.persist ? navigator.storage.persist() : false;
}

storageStatus().then(console.log).catch(console.error);

MDN describes the usual Web Storage allowance as 5 MiB each for localStorage and sessionStorage per origin; available space and accounting can vary with browser settings. Keep cookies small, typically a few KiB, rather than storing documents in them. IndexedDB uses browser-managed origin storage shared with other facilities such as the Cache API. [3][5]

navigator.storage.estimate() provides approximate usage and quota, not a guarantee that the next write succeeds or a separate localStorage counter. persist() can reduce automatic eviction under storage pressure, but cannot prevent manual clearing. Handle QuotaExceededError, remove expendable data and sync critical content to a server or offer an export. [3][10][11]

Cross-tab synchronization, privacy and conflicts

// Uses THEME_KEY, readTheme() and saveTheme() from section 2.
function applyTheme(theme) {
  document.documentElement.dataset.theme = theme;
}

function changeTheme(theme) {
  if (!isTheme(theme)) {
    return false;
  }

  applyTheme(theme);

  return saveTheme(theme);
}

window.addEventListener("storage", (event) => {
  if (
    event.storageArea === localStorage &&
    (event.key === THEME_KEY || event.key === null)
  ) {
    applyTheme(readTheme());
  }
});

applyTheme(readTheme());

The storage event notifies other documents sharing the localStorage area. It does not fire in the window performing the write. For sessionStorage it is limited to same-origin contexts within the same tab. This example updates local theme state directly and responds to changes or clear() in other tabs. [7]

A read-modify-write sequence in localStorage is not a cross-tab transaction. Concurrent writers can lose updates; use IndexedDB transactions for compound updates or server-side version checks. In cross-site embeds, storage may be partitioned or blocked. Do not assume a widget can read state written during a direct visit to its site. [8][12]

Security and application responsibilities

JavaScript running in the app's origin can read and modify localStorage, sessionStorage and IndexedDB. XSS can therefore expose or corrupt their contents. Do not make them the default home for session identifiers or refresh tokens. HttpOnly prevents direct cookie reads but malicious scripts can still issue authenticated requests. SameSite supplements CSRF protection rather than replacing tokens or appropriate origin verification. Authorization must be enforced on the server regardless of local state. [6][13][14]

An offline editor can use localStorage for theme, sessionStorage for view state, a session cookie for authentication and IndexedDB for documents and an outbox. The Cache API can hold HTTP responses such as application assets. An outbox still needs operation IDs, retry rules and conflict resolution; IndexedDB does not sync with a server automatically. Scope records by account and clear private data on logout according to product policy without silently discarding unsaved work. [8][15]

There is no single best storage mechanism. Separating UI state, authentication and domain data lets simple APIs remain simple while transactions provide consistency where needed. Browser storage is a local application layer, not a trust boundary or a guaranteed backup.

JavaScript Browser Storage Web Storage localStorage sessionStorage Cookies IndexedDB Web Security Offline Applications Storage API HttpOnly SameSite

Frequently asked questions

Do localStorage and sessionStorage survive a reload?

Yes, normally both survive reloads, but sessionStorage belongs to a tab session and localStorage has no built-in expiry. [1][2]

Should I store JWTs in localStorage?

Not as the default for session tokens: scripts running in the origin can read them. Consider server-managed sessions using an appropriately configured HttpOnly cookie and CSRF defenses. [6][13][14]

When should I use IndexedDB instead of localStorage?

When you need many records, indexes, transactions or asynchronous operations on larger data sets such as offline documents. [8]

Is IndexedDB a permanent backup?

No. Users can remove it and browser eviction depends on storage policy. Sync or export important data. [3][11]

Does fetch send HttpOnly cookies?

Yes, if cookie scope, SameSite, credentials and browser policies permit it. HttpOnly restricts JavaScript access, not HTTP transmission. [5]

Sources and references

  1. MDN, Web Storage API↩1↩2↩3↩4↩5
  2. MDN, Window.sessionStorage↩1↩2↩3
  3. MDN, Storage quotas and eviction criteria↩1↩2↩3↩4
  4. MDN, Same-origin policy↩
  5. MDN, Set-Cookie↩1↩2↩3↩4↩5↩6↩7
  6. OWASP, Session Management Cheat Sheet↩1↩2↩3↩4
  7. MDN, Window: storage event↩
  8. MDN, Using IndexedDB↩1↩2↩3↩4↩5↩6↩7
  9. MDN, IDBTransaction: complete event↩1↩2
  10. MDN, StorageManager.estimate()↩
  11. MDN, StorageManager.persist()↩1↩2
  12. MDN, Storage Access API↩
  13. OWASP, HTML5 Security Cheat Sheet↩1↩2
  14. OWASP, Cross-Site Request Forgery Prevention↩1↩2
  15. MDN, Cache API↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning