JavaScript Tutorial menu

JavaScript Web Storage (localStorage and sessionStorage)

Web Storage lets a page save small pieces of data inside the user's browser, so they are still there after a reload.

Two Kinds of Storage

localStoragesessionStorage
How long it lastsUntil the user or your code clears itUntil the browser tab is closed
Shared between tabsYes, all tabs of the same websiteNo, each tab has its own
Typical useTheme, language, saved cartA form draft, steps in a checkout
Size limitAbout 5 MB per websiteAbout 5 MB per website

Both are tied to the website's origin (protocol, domain and port). One website cannot read another website's storage.

The Methods

Both objects have the same methods:

MethodWhat it does
setItem(key, value)Saves a value
getItem(key)Reads a value, or null if missing
removeItem(key)Deletes one item
clear()Deletes everything for this website
key(n) and lengthLoop through saved keys

Example

javascript
localStorage.setItem("city", "Karachi");
console.log(localStorage.getItem("city"));      // Karachi
console.log(localStorage.getItem("country"));   // null
localStorage.removeItem("city");

A Remembered Visit Counter

Run this, then click Run again. The number keeps growing, because it is saved in the browser.

Example

html
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>
<button id="reset">Reset</button>

<script>
let visits = 0;
try {
  visits = Number(localStorage.getItem("visits")) || 0;
  visits++;
  localStorage.setItem("visits", visits);
} catch (error) {
  visits = 1;   // storage is blocked (e.g. private mode)
}

document.getElementById("demo").textContent = "You have opened this page " + visits + " time(s).";

document.getElementById("reset").addEventListener("click", () => {
  try { localStorage.removeItem("visits"); } catch (e) {}
  document.getElementById("demo").textContent = "Counter reset.";
});
</script>

</body>
</html>
Try it Yourself »

Storage can throw an error when it is full, or when the browser blocks it (some private windows and strict privacy settings do). Wrap reads and writes in try...catch, and make sure your page still works without storage.

Only Strings Are Stored

Web Storage saves text only. A number comes back as a string, and an object becomes the useless text "[object Object]". Use JSON to save objects and arrays:

Example

javascript
const cart = [{ item: "Lawn suit", qty: 1 }, { item: "Dupatta", qty: 2 }];

localStorage.setItem("cart", JSON.stringify(cart));          // save

const saved = JSON.parse(localStorage.getItem("cart") ?? "[]");   // load
console.log(saved.length, saved[1].item);
Output
2 Dupatta

?? "[]" gives an empty list when nothing is saved yet, so JSON.parse does not fail on null.

Saving a User's Theme

A common real use: remember a setting like dark mode.

Example

html
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 20px; transition: background .3s; }
body.dark { background: #1e1e1e; color: #f0db4f; }
</style>
</head>
<body>

<h2>Workownix Notes</h2>
<button id="toggle">Switch theme</button>
<p>Reload the page: your choice is remembered.</p>

<script>
function loadTheme() {
  try { return localStorage.getItem("theme") ?? "light"; } catch (e) { return "light"; }
}
function saveTheme(theme) {
  try { localStorage.setItem("theme", theme); } catch (e) {}
}

document.body.classList.toggle("dark", loadTheme() === "dark");

document.getElementById("toggle").addEventListener("click", () => {
  const isDark = document.body.classList.toggle("dark");
  saveTheme(isDark ? "dark" : "light");
});
</script>

</body>
</html>
Try it Yourself »

sessionStorage for a Form Draft

sessionStorage is good for a draft that should survive a reload but not stay forever:

Example

javascript
const box = document.getElementById("message");

box.value = sessionStorage.getItem("draft") ?? "";

box.addEventListener("input", () => {
  sessionStorage.setItem("draft", box.value);
});

The storage Event

When localStorage changes in another tab of the same website, the storage event fires on the window. This keeps tabs in sync:

Example

javascript
window.addEventListener("storage", (event) => {
  if (event.key === "theme") {
    document.body.classList.toggle("dark", event.newValue === "dark");
  }
});

What Not to Store

  • Passwords, card numbers or secret tokens. Any script on the page can read storage, so an XSS attack could steal them.
  • Large files or images. The limit is small, and storage is slow for big data. Use IndexedDB for large amounts.
  • Data that must be shared with other devices. Storage lives in one browser only; save it on a server instead.

You can see and edit stored items in the browser DevTools, under Application (Chrome, Edge) or Storage (Firefox).

Exercise

Exercise

What happens to data saved in sessionStorage when the user closes the tab?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp