Web Storage and Cookies
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.stringifyand read them back withJSON.parse, insidetry...catch. localStoragelasts until cleared;sessionStoragelasts until the tab closes. Both are per origin.- The
storageevent tells other tabs of the same site whenlocalStoragechanges. - 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 inlocalStorage.
localStorage and sessionStorage
Both have the same methods:
| Method or property | Description |
|---|---|
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. |
length | The number of stored keys. |
<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>dark
25 string
null
2
null
0Explanation: 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.
localStorage | sessionStorage | |
|---|---|---|
| Lasts | Until removed (by code, or the user clearing site data) | Until the tab is closed |
| Shared between tabs | Yes, every tab of the same origin | No, each tab has its own |
| Survives reload | Yes | Yes |
| Typical use | Settings, preferences, saved drafts | One-time flows, a form in progress |
| Size limit | About 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:
<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>{"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:
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:
<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>lastVisit=2026-01-05; theme=dark
dark
lastVisit=2026-01-05Explanation: 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:
| Attribute | Meaning |
|---|---|
max-age=seconds / expires=date | When it expires (without either, it's deleted when the browser closes) |
path=/ | Which paths it is sent for |
Secure | Sent only over HTTPS |
SameSite=Lax / Strict / None | Whether it is sent with requests from other sites (protects against CSRF) |
HttpOnly | Hidden 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
| Need | Use |
|---|---|
| Login session | A cookie set by the server with HttpOnly; Secure; SameSite |
| User preferences (theme, page size) | localStorage |
| A form in progress, a one-tab flow | sessionStorage |
| Large or structured data, offline apps | IndexedDB (a browser database; usually through a small library) |
| Files and offline caching | The 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:
<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>showPaid saved: true
submitted: 120 for Navika
draft cleared: nullCommon 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
<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>1 2
1Key Takeaways
| Task | Code |
|---|---|
| Save | localStorage.setItem("key", "value") |
| Save an object | localStorage.setItem("key", JSON.stringify(obj)) |
| Read | localStorage.getItem("key") ?? fallback |
| Delete | localStorage.removeItem("key") |
| Tab-only data | sessionStorage.setItem(...) |
| Other tabs changed it | addEventListener("storage", ...) |
Was this tutorial helpful?