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
localStorage | sessionStorage | |
|---|---|---|
| How long it lasts | Until the user or your code clears it | Until the browser tab is closed |
| Shared between tabs | Yes, all tabs of the same website | No, each tab has its own |
| Typical use | Theme, language, saved cart | A form draft, steps in a checkout |
| Size limit | About 5 MB per website | About 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:
| Method | What 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 length | Loop through saved keys |
Example
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
<!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
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);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
<!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
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
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?
