HTML Tutorial · HTML5 Features · Lesson 29 of 34

HTML Web Storage

Save small amounts of data in the browser with localStorage and sessionStorage, and know their limits.

localStorage and sessionStorage

The Web Storage API stores string key-value pairs in the browser for your site's origin.

Lifetime Shared between tabs?
localStorage until deleted by code or the user yes, all tabs of the origin
sessionStorage until the tab is closed no, one tab only
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");        // "dark"
localStorage.removeItem("theme");
localStorage.setItem("cart", JSON.stringify({ items: 2 }));   // store objects as JSON

Handle failures

Storage can be unavailable: private browsing modes, blocked site data, full quota (usually around 5 MB), or a sandboxed frame like this page's preview. Always wrap access in try/catch and keep the page working without it.

Saving a preference with a safe fallbackTry it yourself
<label>Theme
  <select id="theme"><option>light</option><option>dark</option></select>
</label>
<p id="status"></p>
<script>
  const memory = {};
  const store = {
    get(key) { try { return localStorage.getItem(key); } catch { return memory[key] ?? null; } },
    set(key, value) { try { localStorage.setItem(key, value); return "localStorage"; } catch { memory[key] = value; return "memory (storage blocked here)"; } },
  };
  const select = document.getElementById("theme");
  select.value = store.get("theme") || "light";
  select.addEventListener("change", () => {
    const where = store.set("theme", select.value);
    document.getElementById("status").textContent = `Saved "${select.value}" in ${where}.`;
  });
</script>

In this preview, storage is blocked by the sandbox, so the example falls back to memory. Copy it into your own .html file to see the value survive a reload.

What not to store

  • Never store secrets or authentication tokens that scripts shouldn't read: any script on the page (including injected ones) can read storage. Prefer HttpOnly cookies for sessions.
  • Storage is synchronous and small; for larger or structured data use IndexedDB.

Test yourself

Why shouldn't you keep a session token in localStorage?

  1. It expires after one hour
  2. Any script running on the page, including injected ones, can read it
  3. localStorage can't hold strings
  4. Browsers send it with every request
Show answer

Answer: Any script running on the page, including injected ones, can read it

HttpOnly cookies can't be read by JavaScript, which limits the damage of XSS.