JavaScript Storage

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

TL;DR

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

Tips

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

Warnings

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

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

    sessionStorage

    A storage object that maintains key-value data for the duration of the page session.

    sessionStorage.setItem("tabId", "12345");
    const id = sessionStorage.getItem("tabId");
    Tab isolation

    Maintains separate storage instances for each open browser tab, even on the same origin.

    // A new window starts a fresh storage instance
    Identical API

    Shares the same storage interface, methods, and behaviors as localStorage.

    sessionStorage.setItem("key", "val");
    sessionStorage.removeItem("key");
    sessionStorage.clear();

Storing Objects

    JSON.stringify()

    Serializes objects or arrays into strings before saving them to browser storage.

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

    Deserializes stored JSON strings back into usable JavaScript objects or arrays.

    const raw = localStorage.getItem("user");
    const user = JSON.parse(raw);
    console.log(user.name); // "Alice"
    Error handling

    Wraps JSON parsing in try-catch blocks to prevent crashes on invalid data formats.

    try {
      const user = JSON.parse(localStorage.getItem("user"));
    } catch (e) {
      console.error("Invalid JSON stored");
    }

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

In Practice

FAQ