JavaScript Storage

Use localStorage and sessionStorage to persist data in the browser across sessions and refreshes.

TL;DR

  1. Use localStorage to save data that persists across browser sessions.
  2. Use sessionStorage for temporary data cleared when the tab closes.
  3. Store only strings by converting objects to JSON first.

localStorage Basics

    localStorage

    A browser storage object that persists key-value data indefinitely with no expiration date.

    localStorage.setItem("username", "Alice");
    const name = localStorage.getItem("username");
    removeItem()

    Deletes a specific key-value pair from storage by providing the key name.

    localStorage.removeItem("username");
    clear()

    Wipes all stored key-value data for the current domain origin at once.

    localStorage.clear();
    in operator

    Checks if a specific storage key exists in the storage object dictionary.

    if ("username" in localStorage) {
      console.log("Key exists!");
    }

sessionStorage and Storing Objects

    sessionStorage

    A storage object scoped to the current page session.

    sessionStorage.setItem("tab", "5");
    const id = sessionStorage.getItem("tab");
    Tab isolation

    Each open tab gets its own isolated storage instance.

    // A fresh window starts fresh storage
    Identical API

    Same interface and methods as localStorage.

    sessionStorage.setItem("k", "v");
    sessionStorage.removeItem("k");
    JSON.stringify()

    Serializes objects into strings before saving.

    const user = { name: "Alice" };
    localStorage.setItem("u", JSON.stringify(user));
    JSON.parse()

    Deserializes stored JSON back into objects.

    const raw = localStorage.getItem("u");
    const user = JSON.parse(raw); // { name: ...}
    Error handling

    Wraps JSON.parse in try/catch to avoid crashes on bad data.

    try {
      const user = JSON.parse(raw);
    } catch (e) {
      console.error("Bad JSON");
    }

Storage Events

    storage event

    Listens for storage changes on the window object across different origin tabs.

    window.addEventListener("storage", e => {
      console.log(`${e.key} changed to ${e.newValue}`);
    });
    Cross-tab sync

    Notifies other open tabs on the same origin immediately when storage updates.

    // Tab A writes to storage
    localStorage.setItem("theme", "dark");
    
    // Tab B receives storage event automatically
    StorageEvent object

    Exposes modified keys, new values, old values, and the target storage area.

    window.addEventListener("storage", e => {
      if (e.key === "theme") {
        applyTheme(e.newValue);
      }
    });

Best Practices

    QuotaExceededError

    Catches browser storage limit exceptions to avoid crashing applications when disk space runs out.

    try {
      localStorage.setItem("key", largeData);
    } catch (e) {
      if (e.name === "QuotaExceededError") {
        console.warn("Storage limit exceeded!");
      }
    }
    Namespacing

    Prefixes storage keys to prevent overlap conflicts with other third-party scripts.

    localStorage.setItem("myApp_theme", "dark");
    localStorage.setItem("myApp_lang", "en");
    Security warnings

    Avoids storing sensitive authentication tokens, passwords, or personal data in plaintext storage.

    // Avoid storing JWTs in localStorage
    // Secure: use HTTP-only, secure cookies instead

Tips

  1. Use localStorage for user preferences and sessionStorage for temporary state, then sync between tabs using storage events.
  2. Wrap JSON.parse() calls in a try/catch block because corrupted or manually edited storage data throws exceptions.

Warnings

  1. Avoid storing sensitive data like passwords or tokens in localStorage because it is vulnerable to cross-site scripting attacks.
  2. Saving an object directly without JSON.stringify() stores the useless string [object Object] instead of your data.

In Practice

FAQ