Web Storage APIs
Published by Brayan K
Master localStorage, sessionStorage, and IndexedDB to build fast, offline-friendly applications with persistent client-side data.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Choose the storage mechanism and the environment deliberately
localStorage and sessionStorage are synchronous string stores. IndexedDB is asynchronous and stores structured-cloneable values in transactions. None is a server database, an access-control boundary or a promise that data will remain forever. Browser policy, user clearing, private browsing, quotas and eviction can affect availability and retention.
The real API examples below run in your own localhost or HTTPS browser project, in a module script or DevTools. This site’s editor has an isolated origin that blocks persistent storage. Its runnable policy exercises therefore use an explicitly named in-memory test double; they do not pretend to prove persistence, quotas, cross-tab events or IndexedDB transactions.
Observe string conversion and the missing-key sentinel in real localStorage
const key = "lcf:storage-lesson:strings";
const storage = window.localStorage; // Access itself can be denied by browser policy.
try {
storage.removeItem(key); // Touch only this example's named key.
console.log(storage.getItem(key) === null);
storage.setItem(key, false);
console.log(storage.getItem(key), typeof storage.getItem(key));
storage.setItem(key, { theme: "dark" });
console.log(storage.getItem(key)); // Objects are not automatically JSON-encoded.
} finally {
storage.removeItem(key);
}Output
true
false string
[object Object]Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
A missing key returns null, while stored false is the string “false”. Writing an object directly produces its string conversion. Use a versioned encoding and validate decoded data. The examples use reserved practice names and clean up only those names; never replace their cleanup with localStorage.clear on an application origin.
JSON parsing establishes syntax, not the shape your app needs
function validSettings(value) {
return value !== null && typeof value === "object" && !Array.isArray(value) &&
(value.theme === "light" || value.theme === "dark") && typeof value.compact === "boolean";
}
for (const raw of ['null', '[]', '{"theme":"dark","compact":false}', '{"theme":"dark","compact":"false"}']) {
const parsed = JSON.parse(raw);
console.log(validSettings(parsed));
}
try { JSON.parse("broken"); } catch (error) { console.log(error.name); }
// ✅ Expected output:
// false
// false
// true
// false
// SyntaxErrorDo not assume parsed data is trustworthy because your own code originally wrote it. Another same-origin script, a previous application version, a browser extension or manual editing can change it. Deep Dive into JSON, Parsing & Serialization owns JSON encoding limits; this lesson owns storage availability and schema handling.
Origin scope and tab scope answer different questions
A same-origin child frame shares its tab’s sessionStorage area
const key = "lcf:storage-lesson:session";
const frame = document.createElement("iframe");
try {
window.sessionStorage.setItem(key, "parent");
const loaded = new Promise(resolve => frame.onload = resolve);
frame.src = "about:blank";
document.body.append(frame);
await loaded;
console.log(frame.contentWindow.sessionStorage.getItem(key));
frame.contentWindow.sessionStorage.setItem(key, "child");
console.log(window.sessionStorage.getItem(key));
frame.remove();
console.log(window.sessionStorage.getItem(key));
} finally {
frame.remove();
window.sessionStorage.removeItem(key);
}Output
parent
child
childRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
localStorage is scoped to origin, including scheme, host and port; URL paths are not separate storage areas. sessionStorage is also partitioned by the top-level browsing context. Same-origin frames within that tab can share its session area. A newly opened tab can initially copy an opener’s session data, after which the areas diverge; reload and session restore also differ from starting a fresh tab. Do not describe it simply as “deleted on every refresh.”
A storage event is delivered to another eligible document, not the writer
const key = "lcf:storage-lesson:event";
const frame = document.createElement("iframe");
let writerEvents = 0;
const writerListener = event => { if (event.key === key) writerEvents++; };
window.localStorage.removeItem(key);
try {
const loaded = new Promise(resolve => frame.onload = resolve);
frame.src = "about:blank"; document.body.append(frame); await loaded;
window.addEventListener("storage", writerListener);
const received = new Promise(resolve => {
frame.contentWindow.addEventListener("storage", event => {
if (event.key === key) resolve({ key: event.key, oldValue: event.oldValue, newValue: event.newValue });
}, { once: true });
});
window.localStorage.setItem(key, "updated");
const event = await received;
console.log(event.key === key, event.oldValue === null, event.newValue);
console.log(writerEvents);
} finally {
window.removeEventListener("storage", writerListener);
frame.remove(); window.localStorage.removeItem(key);
}Output
true true updated
0Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
Update the writing document’s UI directly; do not wait for its own storage event. An event is a notification, not a cross-tab lock or atomic read-modify-write transaction. Two tabs can read the same count and both write the same incremented value. Use a storage design with an appropriate transaction or coordination model when that race matters.
Catch both acquiring the storage object and using it
function createPreferences(getStorage) {
const key = "lcf:lesson-preferences:v1";
function valid(value) {
return value !== null && typeof value === "object" && !Array.isArray(value) &&
(value.theme === "light" || value.theme === "dark") && typeof value.compact === "boolean";
}
return {
load() {
let raw;
try { raw = getStorage().getItem(key); }
catch (reason) { return { status: "unavailable", reason }; }
if (raw === null) return { status: "missing" };
let stored;
try { stored = JSON.parse(raw); }
catch { return { status: "invalid", cause: "json" }; }
if (!valid(stored) || stored.version !== 1) return { status: "invalid", cause: "shape" };
return { status: "ok", value: { theme: stored.theme, compact: stored.compact } };
},
save(value) {
if (!valid(value)) throw new TypeError("preferences need theme light/dark and boolean compact");
const raw = JSON.stringify({ version: 1, theme: value.theme, compact: value.compact });
try { getStorage().setItem(key, raw); return { status: "saved" }; }
catch (reason) { return { status: "unavailable", reason }; }
}
};
}
const reason = new DOMException("storage unavailable in this test", "SecurityError");
const store = createPreferences(() => { throw reason; });
const loaded = store.load();
const saved = store.save({ theme: "dark", compact: false });
console.log(loaded.status, loaded.reason === reason);
console.log(saved.status, saved.reason === reason);
// ✅ Expected output:
// unavailable true
// unavailable truefunction createPreferences(getStorage) {
const key = "lcf:lesson-preferences:v1";
function valid(value) {
return value !== null && typeof value === "object" && !Array.isArray(value) &&
(value.theme === "light" || value.theme === "dark") && typeof value.compact === "boolean";
}
return {
load() {
let raw;
try { raw = getStorage().getItem(key); }
catch (reason) { return { status: "unavailable", reason }; }
if (raw === null) return { status: "missing" };
let stored;
try { stored = JSON.parse(raw); }
catch { return { status: "invalid", cause: "json" }; }
if (!valid(stored) || stored.version !== 1) return { status: "invalid", cause: "shape" };
return { status: "ok", value: { theme: stored.theme, compact: stored.compact } };
},
save(value) {
if (!valid(value)) throw new TypeError("preferences need theme light/dark and boolean compact");
const raw = JSON.stringify({ version: 1, theme: value.theme, compact: value.compact });
try { getStorage().setItem(key, raw); return { status: "saved" }; }
catch (reason) { return { status: "unavailable", reason }; }
}
};
}
const reason = new DOMException("injected write failure", "QuotaExceededError");
const store = createPreferences(() => ({
getItem: () => null,
setItem: () => { throw reason; }
}));
const result = store.save({ theme: "light", compact: false });
console.log(result.status, result.reason === reason);
console.log(store.load().status);
// ✅ Expected output:
// unavailable true
// missingThese two injected failures test application policy without filling a device or altering browser settings. They are not measurements of storage quotas or proof that every browser reports the same failure. A successful small probe now does not guarantee a later write will succeed. Offer an explicit unavailable state or a clearly labelled temporary fallback rather than claiming persistence.
function memoryStorage() {
const values = new Map();
return {
getItem(key) { return values.has(String(key)) ? values.get(String(key)) : null; },
setItem(key, value) { values.set(String(key), String(value)); },
removeItem(key) { values.delete(String(key)); }
};
}
const first = memoryStorage();
first.setItem("theme", "dark");
const second = memoryStorage();
console.log(first.getItem("theme"), second.getItem("theme"));
console.log(first === second);
// ✅ Expected output:
// dark null
// falseUse IndexedDB request results and transaction completion for different facts
The database examples create and delete only their named practice database. Run them on a disposable development origin, and close other copies of the same practice page. An object store is created or changed during a version upgrade. A request can succeed before its enclosing transaction commits; wait for the transaction’s complete event when reporting a committed write.
Store and retrieve a structured record, then wait for commit
function deletePracticeDatabase(name) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error("close other practice database connections"));
});
}
async function openPracticeDatabase(name, setup) {
await deletePracticeDatabase(name);
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 1);
request.onupgradeneeded = () => setup(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function requestValue(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function transactionDone(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error ?? new DOMException("transaction aborted", "AbortError"));
});
}
const name = "lcf-storage-lesson-record";
const db = await openPracticeDatabase(name, db => db.createObjectStore("items", { keyPath: "id" }));
try {
const original = { id: "A", tags: ["one"], created: new Date("2000-01-01T00:00:00Z") };
const write = db.transaction("items", "readwrite");
const committed = transactionDone(write);
write.objectStore("items").put(original);
await committed;
original.tags.push("later");
const read = db.transaction("items", "readonly");
const finished = transactionDone(read);
const stored = await requestValue(read.objectStore("items").get("A"));
await finished;
console.log(stored.id, stored.tags.join(","), stored.created instanceof Date);
console.log(stored.created.getUTCFullYear(), stored === original);
} finally {
db.close(); await deletePracticeDatabase(name);
}Output
A one true
2000 falseRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
IndexedDB applies structured cloning; this fixed Date survives as a Date and the stored array does not follow a later mutation of the original. Functions and other unsupported values are not made storable by choosing IndexedDB. Deep Copy vs Shallow Copy & Data Structures owns structured-clone boundaries.
A successful request can still be rolled back by an aborted transaction
function deletePracticeDatabase(name) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error("close other practice database connections"));
});
}
async function openPracticeDatabase(name, setup) {
await deletePracticeDatabase(name);
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 1);
request.onupgradeneeded = () => setup(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function requestValue(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function transactionDone(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error ?? new DOMException("transaction aborted", "AbortError"));
});
}
const name = "lcf-storage-lesson-abort";
const db = await openPracticeDatabase(name, db => db.createObjectStore("items", { keyPath: "id" }));
try {
const transaction = db.transaction("items", "readwrite");
const finished = transactionDone(transaction);
const request = transaction.objectStore("items").put({ id: "A" });
request.onsuccess = () => { console.log("request succeeded"); transaction.abort(); };
try { await finished; } catch (error) { console.log(error.name); }
const read = db.transaction("items", "readonly"), done = transactionDone(read);
const value = await requestValue(read.objectStore("items").get("A"));
await done;
console.log(value === undefined);
} finally { db.close(); await deletePracticeDatabase(name); }Output
request succeeded
AbortError
trueRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
A uniqueness failure aborts the whole transaction by default
function deletePracticeDatabase(name) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error("close other practice database connections"));
});
}
async function openPracticeDatabase(name, setup) {
await deletePracticeDatabase(name);
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 1);
request.onupgradeneeded = () => setup(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function requestValue(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function transactionDone(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error ?? new DOMException("transaction aborted", "AbortError"));
});
}
const name = "lcf-storage-lesson-unique";
const db = await openPracticeDatabase(name, db => {
const items = db.createObjectStore("items", { keyPath: "id" });
items.createIndex("byCode", "code", { unique: true });
});
try {
const transaction = db.transaction("items", "readwrite"), finished = transactionDone(transaction);
const items = transaction.objectStore("items");
items.add({ id: "A", code: "same" }); items.add({ id: "B", code: "same" });
try { await finished; } catch (error) { console.log(error.name); }
const read = db.transaction("items", "readonly"), done = transactionDone(read);
const count = await requestValue(read.objectStore("items").count()); await done;
console.log(count);
} finally { db.close(); await deletePracticeDatabase(name); }Output
ConstraintError
0Run in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
The duplicate index value causes an unhandled request error and the transaction aborts, including its earlier write. This example deliberately does not prevent the request error’s default behaviour. Error-event handling can affect transaction behaviour, so do not add preventDefault merely to hide a message.
Transaction lifetime and database version upgrades are explicit boundaries
A completed transaction cannot accept another write
function deletePracticeDatabase(name) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error("close other practice database connections"));
});
}
async function openPracticeDatabase(name, setup) {
await deletePracticeDatabase(name);
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 1);
request.onupgradeneeded = () => setup(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function requestValue(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function transactionDone(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error ?? new DOMException("transaction aborted", "AbortError"));
});
}
const name = "lcf-storage-lesson-inactive";
const db = await openPracticeDatabase(name, db => db.createObjectStore("items", { keyPath: "id" }));
try {
const transaction = db.transaction("items", "readwrite"), finished = transactionDone(transaction);
const items = transaction.objectStore("items"); items.put({ id: "A" });
await finished;
try { items.put({ id: "B" }); } catch (error) { console.log(error.name); }
} finally { db.close(); await deletePracticeDatabase(name); }Output
TransactionInactiveErrorRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
Do unrelated network or user-interaction work before opening a short transaction. Awaiting unrelated tasks inside a transaction can leave it inactive before the next request is queued. Request success and transaction completion should each have an owner; do not mix a callback API with arbitrary awaits and assume the transaction remains open.
An older open connection can block a schema upgrade
function deletePracticeDatabase(name) {
return new Promise((resolve, reject) => {
const request = window.indexedDB.deleteDatabase(name);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onblocked = () => reject(new Error("close other practice database connections"));
});
}
async function openPracticeDatabase(name, setup) {
await deletePracticeDatabase(name);
return new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 1);
request.onupgradeneeded = () => setup(request.result);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function requestValue(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
function transactionDone(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error ?? new DOMException("transaction aborted", "AbortError"));
});
}
const name = "lcf-storage-lesson-upgrade";
const first = await openPracticeDatabase(name, db => db.createObjectStore("items"));
const trace = [];
first.onversionchange = () => trace.push("versionchange");
const second = await new Promise((resolve, reject) => {
const request = window.indexedDB.open(name, 2);
request.onblocked = () => { trace.push("blocked"); first.close(); };
request.onupgradeneeded = () => { trace.push("upgrade"); request.result.createObjectStore("settings"); };
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
try {
console.log(trace.join(","));
console.log(second.objectStoreNames.contains("items"), second.objectStoreNames.contains("settings"));
} finally { first.close(); second.close(); await deletePracticeDatabase(name); }Output
versionchange,blocked,upgrade
true trueRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
An application should normally respond to versionchange by closing its connection and guiding the user to reload when appropriate. The example intentionally leaves it open until blocked to demonstrate the sequence. Schema upgrades, data migrations and incompatible older tabs need a plan; a larger version number alone does not migrate record shapes.
Keep stored preferences small, versioned and explicitly recoverable
Use the same preference policy against genuine localStorage
function createPreferences(getStorage) {
const key = "lcf:lesson-preferences:v1";
function valid(value) {
return value !== null && typeof value === "object" && !Array.isArray(value) &&
(value.theme === "light" || value.theme === "dark") && typeof value.compact === "boolean";
}
return {
load() {
let raw;
try { raw = getStorage().getItem(key); }
catch (reason) { return { status: "unavailable", reason }; }
if (raw === null) return { status: "missing" };
let stored;
try { stored = JSON.parse(raw); }
catch { return { status: "invalid", cause: "json" }; }
if (!valid(stored) || stored.version !== 1) return { status: "invalid", cause: "shape" };
return { status: "ok", value: { theme: stored.theme, compact: stored.compact } };
},
save(value) {
if (!valid(value)) throw new TypeError("preferences need theme light/dark and boolean compact");
const raw = JSON.stringify({ version: 1, theme: value.theme, compact: value.compact });
try { getStorage().setItem(key, raw); return { status: "saved" }; }
catch (reason) { return { status: "unavailable", reason }; }
}
};
}
const key = "lcf:lesson-preferences:v1";
try {
window.localStorage.removeItem(key);
const store = createPreferences(() => window.localStorage);
console.log(store.load().status);
console.log(store.save({ theme: "dark", compact: false }).status);
const loaded = store.load();
console.log(loaded.status, loaded.value.theme, loaded.value.compact);
} finally { window.localStorage.removeItem(key); }Output
missing
saved
ok dark falseRun in your own browser project on localhost or HTTPS, in a module script or DevTools. This example needs real browser storage; the site editor isolates it.
The provider is acquired inside each operation’s try/catch, so blocked access is represented as unavailable. Loading invalid data does not silently erase or overwrite it. The caller decides whether to reset, migrate or ask the user. Extra fields are deliberately excluded from saved preferences. Do not store credentials or sensitive data merely because a key is hard to guess: same-origin scripts can access these stores.
Guided exercise: distinguish missing data from stored false
This exercise uses the in-memory test double only to check the string/missing contract. Fill each literal hint; no persistence claim is made.
function memoryStorage() {
const values = new Map();
return {
getItem(key) { return values.has(String(key)) ? values.get(String(key)) : null; },
setItem(key, value) { values.set(String(key), String(value)); },
removeItem(key) { values.delete(String(key)); }
};
}
const storage = memoryStorage();
console.log(storage.getItem("compact") === ___); // 👉 replace ___ with null
storage.setItem("compact", JSON.stringify(false));
const raw = storage.___("compact"); // 👉 replace ___ with getItem
console.log(JSON.___(raw) === false); // 👉 replace ___ with parse
// ✅ Expected output:
// true
// trueIndependent brief: a versioned preference adapter with honest outcomes
Implement createPreferences(getStorage) with load and save. The provider offers synchronous getItem/setItem and may throw when accessed. Use only lcf:lesson-preferences:v1. Save only version 1, theme light/dark and a boolean compact, excluding other fields; reject invalid caller input before accessing storage.
Load returns missing for null, invalid with json or shape for malformed/unsupported content, unavailable with the exact access reason, or ok with a fresh preference value. Save returns saved only after setItem succeeds, otherwise unavailable with the exact reason. Loading must never write or delete. Test all four load outcomes, a save failure, zero writes on invalid input, false preservation, unsupported version, extra-field exclusion and fresh decoded results.
Reference notes
MDN documents the Web Storage APIs, storage events, IndexedDB transactions and upgrades, and quotas and eviction. No universal quota number, permanent-retention guarantee or security claim is inferred from these small checks.
Practice quiz
What does a missing localStorage.getItem key return?
- null
- undefined
- An empty object
- false
Answer: null. Web Storage distinguishes missing keys with null; stored values are strings.
What does this complete program print? const raw=JSON.stringify(false);console.log(typeof raw,JSON.parse(raw)===false);
- boolean true
- string true
- string false
- boolean false
Answer: string true. JSON text can preserve false without treating it as missing.
An IndexedDB put request succeeds, but its transaction then aborts. Which event would have established a committed transaction?
- The request success alone
- The database open event
- The transaction complete event
- Any storage event
Answer: The transaction complete event. Request success precedes the final transaction outcome; abort can roll the write back.
Which document receives the storage event for a localStorage change?
- The writer only
- Every page on the internet
- Every tab regardless of origin
- Another eligible document sharing that storage area
Answer: Another eligible document sharing that storage area. The writing document does not receive its own storage event.
What does this complete program print? const value=JSON.parse('{"theme":"dark","compact":"false"}');console.log(typeof value.compact==="boolean");
- false
- true
- undefined
- TypeError
Answer: false. Valid JSON syntax does not establish the application shape.
What should an existing IndexedDB connection normally do when a newer schema triggers versionchange?
- Ignore it forever
- Close the connection and coordinate the update
- Call localStorage.clear
- Change its version property directly
Answer: Close the connection and coordinate the update. Closing the old connection lets the pending upgrade proceed; migration still needs an explicit plan.
What does this complete program print? const first=JSON.parse('{"compact":false}'),second=JSON.parse('{"compact":false}');console.log(first===second,first.compact===second.compact);
- true true
- false false
- false true
- true false
Answer: false true. Separate parses produce distinct objects containing the same boolean value.
What does this complete program print? const reason={blocked:true};function provider(){throw reason}try{provider().getItem("key")}catch(error){console.log(error===reason)}
- false
- undefined
- TypeError
- true
Answer: true. Acquiring the storage provider can fail before a method is called.
Continue this course
- Previous: Advanced Fetch API Patterns (Retry, Timeout, AbortController)
- Next: Building Custom APIs with Fetch & Async Logic — Design reusable API modules with auth, caching, and error handling built in
- Quick reference: JavaScript cheat sheet
- From the blog: How to Learn to Code Fast (Without Burning Out)