Sikau

Web essentials · Day 5 · about 25 min

Storage and cookies

Where browsers keep data — and when to use which.

Remembering things

Your theme choice, a draft message, whether you're signed in — browsers have several places to keep data, each with different lifetimes and rules. Choosing the right one matters for both convenience and security.

The options

  • localStorage — strings by key, kept until cleared. Per site. Good for preferences and drafts. Readable by any script on the page, so never store secrets there.
  • sessionStorage — like localStorage, but only for this tab, gone when it closes.
  • Cookies — small values sent to the server with every request. Sign-in sessions use cookies marked HttpOnly (JavaScript can't read them), Secure (HTTPS only) and SameSite (limits cross-site sending).
  • IndexedDB — a real database in the browser for large or structured data (offline apps).
function loadSettings() {
  try {
    const raw = localStorage.getItem("settings:v1");
    return { theme: "light", ...(raw ? JSON.parse(raw) : {}) };
  } catch {
    return { theme: "light" };
  }
}
function saveSettings(s) {
  try {
    localStorage.setItem("settings:v1", JSON.stringify(s));
  } catch {
    // Storage full or blocked (e.g. private mode): carry on without saving.
  }
}
saveSettings({ theme: "dark" });
console.log(loadSettings());

The rest of this lesson

  • Versioned, defensive storageexplain
  • Cookies and securityexplain
  • Where should a login token live?predict
  • Where should it live?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials