HTML Local Storage

Beginner
12 min read
Updated: Nov 2026
5 examples
Web Storage API

Definition and Usage

Local Storage is the browser’s localStorage object from the Web Storage API. From a <script> in your HTML page you save string key-value pairs for the document’s origin. Data is saved across browser sessions—it remains after you close the tab or browser until you remove it or the user clears site data.

How is localStorage different from sessionStorage?

Both use the same Storage methods. localStorage has no expiration and is shared by every tab of that origin. sessionStorage lasts only for one tab’s page session and clears when that tab closes.

How is this useful in HTML pages?

Remember a dark/light theme, remember last visited section, keep a simple shopping cart on the client, or restore form defaults on return visits—without sending that data to the server on every request (unlike cookies).

When should you prefer localStorage?

Use it for small, non-sensitive preferences that should survive reloads and new visits. For large or structured offline data, use IndexedDB. For tab-only drafts, use sessionStorage.

Strings only (UTF-16).

Keys and values are strings. Integer keys are coerced to strings. Store objects with JSON.stringify / JSON.parse.

Not a vault.

Same-origin scripts (including XSS) can read localStorage. Never store passwords, tokens, or payment data there.

HTTP ≠ HTTPS storage.

http://example.com and https://example.com have separate localStorage areas. Private browsing data is cleared when the last private tab closes.

HTML / Script Syntax

Call methods on localStorage from a script in your HTML document:

JS
localStorage.setItem("key", "value");
var data = localStorage.getItem("key");   // string or null
localStorage.removeItem("key");
localStorage.clear();                     // remove all keys for this origin
localStorage.key(0);                      // name of key at index
localStorage.length;                      // number of keys
HTML
<button type="button" id="themeBtn">Toggle theme</button>
<script>
  var saved = localStorage.getItem("theme");
  if (saved) document.body.setAttribute("data-theme", saved);

  document.getElementById("themeBtn").onclick = function () {
    var next = document.body.getAttribute("data-theme") === "dark" ? "light" : "dark";
    document.body.setAttribute("data-theme", next);
    localStorage.setItem("theme", next);
  };
</script>

Core HTML Concepts

How local storage fits into HTML pages and the browser:

ConceptMeaning
localStoragePer-origin Storage object that persists across sessions
OriginScheme + host + port; storage is separate per origin
setItem / getItemWrite and read string values
removeItem / clearDelete one key or all keys for this origin
key / lengthInspect stored keys for debugging
Shared tabsAll tabs of the origin see the same localStorage
Not in HTTPUnlike cookies, values are not sent with page requests
sessionStorageTab-scoped storage that clears when the tab closes
storage eventOther tabs can react when localStorage changes (see onstorage)

localStorage vs sessionStorage

localStoragesessionStorage
ScopeAll tabs of the originOne tab (top-level browsing context)
LifetimeUntil cleared by script or userUntil tab/window closes
Survives browser restart?YesNo
Best forTheme, prefs, lasting client dataDrafts, wizards, one-visit state

How to Use Local Storage in HTML

Wire persistent storage to page load and user actions.

  1. Add HTML controls (buttons, selects, inputs) with ids.
  2. On save or change, call localStorage.setItem(key, value).
  3. On page load, getItem and apply the value to the HTML (classes, attributes, form fields).
  4. Use removeItem for one preference, or clear to wipe the origin’s store.
  5. Serialize objects with JSON; keep payloads small (~5 MB typical limit).
GoalPattern
Save a stringlocalStorage.setItem("greeting", "Hello")
Restore on loadvar v = localStorage.getItem("greeting")
Store an objectsetItem("cart", JSON.stringify(obj))
Forget one keylocalStorage.removeItem("greeting")
Reset all keyslocalStorage.clear()

Live Preview

Save a value into this origin’s localStorage. Close the tab and return—it should still be there until you clear it.

Uses key ctf-ls-demo for this site origin. Try Save, then open another tab of this page—Load should see the same value.

localStorage status

No value saved yet.

localStorage.getItem("ctf-ls-demo") → null

HTML Examples

Five patterns: save/read strings, JSON objects, remove keys, list keys, and a full HTML page demo.

Example 1 — Save and Read a String

JS
localStorage.setItem("myCat", "Tom");
var cat = localStorage.getItem("myCat");
console.log(cat); // Tom
Try It Yourself

How It Works

  1. setItem writes (or overwrites) a key for this origin.
  2. getItem returns the string, or null if missing.
  3. Persists after reload and after closing the browser.
  4. Shared — another tab on the same origin can read the same key.

Example 2 — Store an Object with JSON

JS
var cart = { items: 2, total: 19.99 };
localStorage.setItem("cart", JSON.stringify(cart));

var loaded = JSON.parse(localStorage.getItem("cart"));
console.log(loaded.total); // 19.99
Try It Yourself

How It Works

  1. stringify turns the object into a string Web Storage accepts.
  2. parse rebuilds the object after getItem.
  3. Guard parse with try/catch if data might be corrupt.
  4. Quota — very large strings may throw QuotaExceededError.

Example 3 — Remove One Key

JS
localStorage.setItem("temp", "draft");
localStorage.removeItem("temp");
console.log(localStorage.getItem("temp")); // null
Try It Yourself

How It Works

  1. removeItem deletes one key; missing keys do not throw.
  2. clear() wipes every key for this origin’s localStorage.
  3. User clear — clearing site data in browser settings also removes it.
  4. Other tabs can listen via the storage event when you remove a key.

Example 4 — List All Keys

JS
for (var i = 0; i < localStorage.length; i++) {
  var key = localStorage.key(i);
  console.log(key, localStorage.getItem(key));
}
Try It Yourself

How It Works

  1. length is how many keys this origin currently stores.
  2. key(i) returns the key name at that index.
  3. Debug tip — list keys when an HTML preference fails to restore.
  4. Order of keys is not guaranteed across browsers.

Example 5 — Full HTML Page (Save / Retrieve / Clear)

Connect localStorage to HTML buttons so data survives browser restarts:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Local Storage Example</title>
</head>
<body>
  <h1>HTML Local Storage Example</h1>
  <button type="button" id="save">Save to Local Storage</button>
  <button type="button" id="retrieve">Retrieve from Local Storage</button>
  <button type="button" id="remove">Remove from Local Storage</button>
  <button type="button" id="clear">Clear All Local Storage</button>
  <p id="output"></p>

  <script>
    document.getElementById("save").onclick = function () {
      localStorage.setItem("greeting", "Hello, World!");
      document.getElementById("output").textContent = "Data saved!";
    };
    document.getElementById("retrieve").onclick = function () {
      var greeting = localStorage.getItem("greeting");
      document.getElementById("output").textContent =
        greeting ? greeting : "No data found";
    };
    document.getElementById("remove").onclick = function () {
      localStorage.removeItem("greeting");
      document.getElementById("output").textContent = "Data removed!";
    };
    document.getElementById("clear").onclick = function () {
      localStorage.clear();
      document.getElementById("output").textContent = "All data cleared!";
    };
  </script>
</body>
</html>
Try It Yourself

How It Works

  1. HTML provides the UI; the script talks to localStorage.
  2. Save writes greeting for the whole origin.
  3. Close and reopen the browser—Retrieve still finds the value.
  4. Remove / Clear delete one key or everything for this origin.

Edge Cases & Pitfalls

Most surprises come from origin rules, string-only values, or blocked storage.

protocol

HTTP vs HTTPS

They are different origins for storage. Data saved on http will not appear on https for the same host.

types

Storing objects raw

Non-strings are coerced. Prefer JSON so you do not get "[object Object]".

null

Forgetting null checks

getItem returns null when missing. Guard before writing into HTML inputs or classes.

file

file: URLs

Behavior is undefined across browsers. Do not rely on localStorage when opening HTML files from disk—use a local server.

quota

QuotaExceededError

Large strings can throw. Catch errors around setItem for big payloads.

private

Private / incognito

Data is typically cleared when the last private tab closes. Do not assume permanent storage in private mode.

Browser Support

localStorage is part of the Web Storage API and is supported in all modern browsers.

✓ Baseline · Widely available

localStorage in HTML pages

Persistent Web Storage works across current browsers for same-origin HTML documents.

100% localStorage support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Web Storage localStorage Universal

Bottom line: Use localStorage for lasting client preferences—support is widespread; watch privacy settings and file: origins.

Key Takeaways

  • Persists across sessions until cleared; shared by all tabs of the origin.
  • Not cookies — values stay in the browser and are not sent with HTML requests.
  • API: setItem, getItem, removeItem, clear.
  • Wire to HTML on load to restore theme, prefs, and form defaults.

One line: From your HTML page’s script, use localStorage for lasting, origin-scoped key-value data that outlives the browser session.

Frequently Asked Questions

localStorage is a Web Storage API on the window object. From a script in your HTML page you store string key-value pairs for the document’s origin. Data survives closing the browser until you remove it or the user clears site data.
localStorage is shared across all tabs of the same origin and has no expiration. sessionStorage is per tab and clears when that tab’s page session ends.
No. Unlike cookies, localStorage stays in the browser and is not attached to HTTP requests. Use it for client-only preferences such as theme or UI layout.
On change, call localStorage.setItem(key, value). On page load, getItem and apply the value to your HTML (for example set a class on body or fill an input).
Only strings are stored. Use JSON.stringify before setItem and JSON.parse after getItem when you need objects.
Invalid origins (for example some file: pages) or privacy settings that block site data can prevent storage. Prefer testing over http(s). Never store secrets—same-origin scripts can read localStorage.

Practice in the editor

Open the full save/retrieve HTML demo and confirm data survives a browser restart.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful