Web Storage and Cookies

Updated · 8 min read
mediumES2026javascriptlocalstoragesessionstoragecookiessecurity

Web Storage lets a page save small amounts of data in the browser so it survives a reload: settings, a draft, the last filter used. It comes in two forms: localStorage, which keeps data until it is deleted, and sessionStorage, which keeps it only for the life of the tab. Cookies are an older mechanism that the browser sends to the server with every request, which makes them right for sessions and wrong for app data. Knowing which to use, and what must never be stored in any of them, is an important security skill.

In One Minute

  • localStorage.setItem(key, value), getItem(key), removeItem(key), clear(). Values are strings only.
  • Store objects with JSON.stringify and read them back with JSON.parse, inside try...catch.
  • localStorage lasts until cleared; sessionStorage lasts until the tab closes. Both are per origin.
  • The storage event tells other tabs of the same site when localStorage changes.
  • Cookies travel to the server on every request; use them for sessions (set by the server as HttpOnly). Never store passwords, tokens or personal data in localStorage.

localStorage and sessionStorage

Both have the same methods:

Method or propertyDescription
setItem(key, value)It is used to save a value (converted to a string).
getItem(key)It is used to read a value; returns null if the key doesn't exist.
removeItem(key)It is used to delete one key.
clear()It is used to delete every key for this origin.
key(index)It is used to get the name of the key at a position.
lengthThe number of stored keys.
storage.html
<script>
  localStorage.setItem("theme", "dark");
  localStorage.setItem("pageSize", 25);

  console.log(localStorage.getItem("theme"));
  console.log(localStorage.getItem("pageSize"), typeof localStorage.getItem("pageSize"));
  console.log(localStorage.getItem("missing"));
  console.log(localStorage.length);

  localStorage.removeItem("theme");
  console.log(localStorage.getItem("theme"));
  localStorage.clear();
  console.log(localStorage.length);
</script>
Output
dark
25 string
null
2
null
0

Explanation: the number 25 came back as the string "25": storage only holds strings, so convert when reading (Number(...)). A missing key returns null, not undefined.

localStoragesessionStorage
LastsUntil removed (by code, or the user clearing site data)Until the tab is closed
Shared between tabsYes, every tab of the same originNo, each tab has its own
Survives reloadYesYes
Typical useSettings, preferences, saved draftsOne-time flows, a form in progress
Size limitAbout 5 MB per origin (varies by browser)Same

Origin means the combination of scheme, host and port: https://www.example.com and https://app.example.com have separate storage.

Storing Objects as JSON

To store anything other than a string, convert it to JSON text with JSON.stringify, and convert it back with JSON.parse. Because stored data can be missing, old, or edited by hand, reading should be defensive:

json-storage.html
<script>
  const KEY = "feeTracker.settings";
  const DEFAULTS = { currency: "USD", pageSize: 25, showPaid: true };

  function loadSettings() {
    try {
      const saved = JSON.parse(localStorage.getItem(KEY) ?? "null");
      return { ...DEFAULTS, ...saved };
    } catch {
      return { ...DEFAULTS };
    }
  }

  function saveSettings(settings) {
    localStorage.setItem(KEY, JSON.stringify(settings));
  }

  console.log(JSON.stringify(loadSettings()));
  saveSettings({ ...loadSettings(), pageSize: 50 });
  console.log(JSON.stringify(loadSettings()));

  localStorage.setItem(KEY, "{not valid json");
  console.log(JSON.stringify(loadSettings()));
</script>
Output
{"currency":"USD","pageSize":25,"showPaid":true}
{"currency":"USD","pageSize":50,"showPaid":true}
{"currency":"USD","pageSize":25,"showPaid":true}

Explanation: with nothing saved, getItem returns null, JSON.parse("null") gives null, and spreading null adds nothing, so the defaults are used. After saving, the stored value overrides one default. When the stored text is corrupted, JSON.parse throws, and the catch falls back to the defaults instead of breaking the page.

Also wrap writes in try...catch when the data can be large: when the quota is full, setItem throws a QuotaExceededError. Some private-browsing modes and strict privacy settings make storage unavailable or empty, so pages must keep working without it.

The storage Event

When one tab changes localStorage, every other open tab of the same origin receives a storage event. That lets a setting change in one tab update the others, or a logout in one tab log out them all:

storage-event.js
window.addEventListener("storage", (event) => {
  if (event.key !== "feeTracker.settings") return;
  console.log("Settings changed in another tab:", event.oldValue, "→", event.newValue);
  applySettings(JSON.parse(event.newValue ?? "{}"));
});

The event fires only in the other tabs, not in the one that made the change, so this example needs two tabs and is shown without output. For richer tab-to-tab messages, use BroadcastChannel.

Cookies

A cookie is a small piece of text the browser stores for a site and sends to the server with every request to that site. Servers use cookies mainly for sessions ("this request comes from Navika, who logged in"). JavaScript can read and write cookies through document.cookie, but the API is awkward:

cookies.html
<script>
  document.cookie = "lastVisit=2026-01-05; max-age=86400; path=/; SameSite=Lax; Secure";
  document.cookie = "theme=dark; path=/; Secure";

  console.log(document.cookie);

  const cookies = Object.fromEntries(document.cookie.split("; ").map((c) => c.split("=")));
  console.log(cookies.theme);

  document.cookie = "theme=; max-age=0; path=/; Secure";
  console.log(document.cookie);
</script>
Output
lastVisit=2026-01-05; theme=dark
dark
lastVisit=2026-01-05

Explanation: assigning to document.cookie adds or updates one cookie (it doesn't replace them all). Reading it returns every visible cookie as one string, which you must split yourself. Deleting means setting max-age=0. The attributes after the value control the cookie's behavior:

AttributeMeaning
max-age=seconds / expires=dateWhen it expires (without either, it's deleted when the browser closes)
path=/Which paths it is sent for
SecureSent only over HTTPS
SameSite=Lax / Strict / NoneWhether it is sent with requests from other sites (protects against CSRF)
HttpOnlyHidden from JavaScript entirely; can only be set by the server

The newer Cookie Store API (cookieStore.get, cookieStore.set) is a promise-based replacement for document.cookie (it runs in current Chrome; check "cookieStore" in window before relying on it elsewhere).

Which One to Use

NeedUse
Login sessionA cookie set by the server with HttpOnly; Secure; SameSite
User preferences (theme, page size)localStorage
A form in progress, a one-tab flowsessionStorage
Large or structured data, offline appsIndexedDB (a browser database; usually through a small library)
Files and offline cachingThe Cache API with a Service Worker

Security and Privacy

Also:

  • Storage is visible and editable in DevTools (Application panel): never trust stored values without validating them.
  • Data stays in the browser after the user leaves; on a shared computer, the next person can see it. Clear sensitive drafts when they are submitted.
  • In the US and elsewhere, privacy laws and good practice say to store only what you need, and to tell users what you store and why. Cookies used for tracking need consent in many regions.

In Practice

The Fee Tracker remembers the reader's view settings across visits and keeps a payment draft only for the current tab, clearing it after submission:

remember.html
<label><input type="checkbox" id="toggle"> Show paid students</label>
<input id="draft">
<button id="submit">Submit</button>
<script>
  const toggle = document.querySelector("#toggle");
  const draft = document.querySelector("#draft");

  toggle.checked = localStorage.getItem("feeTracker.showPaid") === "true";
  draft.value = sessionStorage.getItem("feeTracker.draft") ?? "";

  toggle.addEventListener("change", () => {
    localStorage.setItem("feeTracker.showPaid", String(toggle.checked));
    console.log("showPaid saved:", localStorage.getItem("feeTracker.showPaid"));
  });
  draft.addEventListener("input", () => sessionStorage.setItem("feeTracker.draft", draft.value));
  document.querySelector("#submit").addEventListener("click", () => {
    console.log("submitted:", sessionStorage.getItem("feeTracker.draft"));
    sessionStorage.removeItem("feeTracker.draft");
    console.log("draft cleared:", sessionStorage.getItem("feeTracker.draft"));
  });
</script>
Output
showPaid saved: true
submitted: 120 for Navika
draft cleared: null

Common Mistakes

Storing objects without JSON.stringify. setItem("s", { a: 1 }) stores the string "[object Object]".

Calling JSON.parse without try...catch. Corrupted data crashes the page.

Treating stored numbers and booleans as their types. "false" is truthy. Compare strings or parse them.

Putting tokens or personal data in localStorage. Any script on the page can read it.

Practice

Challenge: Write visitCount() that increments a counter stored in localStorage under "feeTracker.visits" and returns the new count, treating a missing or invalid value as 0.

Show solution
visits.html
<script>
  function visitCount() {
    const current = Number.parseInt(localStorage.getItem("feeTracker.visits") ?? "0", 10);
    const next = (Number.isNaN(current) ? 0 : current) + 1;
    localStorage.setItem("feeTracker.visits", String(next));
    return next;
  }
  console.log(visitCount(), visitCount());
  localStorage.setItem("feeTracker.visits", "oops");
  console.log(visitCount());
</script>
Output
1 2
1

Quick check: Web storage

3 questions
1What does localStorage.getItem("count") return after setItem("count", 5)?
2Which lasts only until the tab is closed?
3Where should a login session token be stored?

Key Takeaways

TaskCode
SavelocalStorage.setItem("key", "value")
Save an objectlocalStorage.setItem("key", JSON.stringify(obj))
ReadlocalStorage.getItem("key") ?? fallback
DeletelocalStorage.removeItem("key")
Tab-only datasessionStorage.setItem(...)
Other tabs changed itaddEventListener("storage", ...)

Was this tutorial helpful?

Lesson 80 of 139