IndexedDB
Published by Brayan K
IndexedDB is a transactional, asynchronous database built into the browser that stores large amounts of structured data — objects, arrays, even files — keyed for fast lookup and queryable through indexes.
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 keys and indexes from the query you need
An object store is addressed by primary key. An index gives another ordered access path derived from stored values; it is not an arbitrary SQL WHERE expression. Start with a concrete request: open tasks at or below a priority, ordered by priority and then ID. A compound index can encode that order.
function planTaskQuery(maxPriority, limit) {
if (!Number.isInteger(maxPriority) || maxPriority < 0 || maxPriority > 9) throw new RangeError("invalid priority limit");
if (!Number.isInteger(limit) || limit < 1 || limit > 20) throw new RangeError("invalid row limit");
return { lower: ["open", 0], upper: ["open", maxPriority, "\uffff"], limit };
}
// This pure planner constructs data. The real IndexedDB query is checked below.
const query = planTaskQuery(3, 5);
console.log(JSON.stringify(query.lower));
console.log(JSON.stringify(query.upper));
console.log(query.limit);
// ✅ Expected output:
// ["open",0]
// ["open",3,""]
// 5Read an actual compound index in key order
async function openTasks() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-course-example", 1);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore("tasks", { keyPath: "id" });
store.createIndex("byStatusPriorityId", ["status", "priority", "id"]);
};
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function seed(db, rows) {
return new Promise((resolve, reject) => {
const tx = db.transaction("tasks", "readwrite");
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
const store = tx.objectStore("tasks");
rows.forEach(row => store.put(row));
});
}
const db = await openTasks();
try {
await seed(db, [
{ id: "z", status: "open", priority: 2, title: "Last tie" },
{ id: "a", status: "open", priority: 2, title: "First tie" },
{ id: "b", status: "closed", priority: 0, title: "Closed" },
{ id: "c", status: "open", priority: 1, title: "Earlier priority" }
]);
const result = await new Promise((resolve, reject) => {
let rows;
const tx = db.transaction("tasks", "readonly");
tx.oncomplete = () => resolve(rows);
tx.onabort = () => reject(tx.error);
const range = IDBKeyRange.bound(["open", 0], ["open", 2, "\uffff"]);
const request = tx.objectStore("tasks").index("byStatusPriorityId").getAll(range, 10);
request.onsuccess = () => { rows = request.result; };
});
console.log(result.map(row => row.id).join(", "));
} finally { db.close(); }Output
c, a, zRun 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.
This panel executes in real browser storage on a fresh local origin. The site editor isolates storage, so it is a checked browser-project example rather than a simulated database in the editor. Web Storage APIs (localStorage, sessionStorage, IndexedDB) owns transaction completion and storage lifetime fundamentals. This lesson concentrates on keys, indexes, cursors and schema changes.
Key types and compound prefixes affect ordering
Compare actual IndexedDB key ordering and invalid key types
console.log(indexedDB.cmp(2, 10));
console.log(indexedDB.cmp(10, "2"));
console.log(indexedDB.cmp(["open", 2], ["open", 2, "a"]));
for (const key of [true, null, NaN, {}]) {
try { indexedDB.cmp(key, key); }
catch (error) { console.log(error.name); }
}
const range = IDBKeyRange.bound(["open", 0], ["open", 2, "\uffff"]);
console.log(range.includes(["open", 2, "a"]), range.includes(["closed", 1, "a"]));Output
-1
-1
-1
DataError
DataError
DataError
DataError
true 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.
Numbers, strings and arrays of valid keys are different ordered key types. A boolean status is not a valid key, so this schema uses the strings open and closed. Compound arrays compare lexicographically; a shorter matching prefix comes before a longer array. The upper string sentinel in this lesson is justified by the restricted lowercase ASCII ID contract, not a universal bound for arbitrary nested keys.
Use lowerOpen and upperOpen deliberately when a range should exclude an endpoint. IDBKeyRange bounds describe the index key ordering, not a JavaScript predicate that can inspect every field.
An index can contain fewer entries than its object store
Missing indexed fields do not make the stored record disappear
async function openTasks() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-course-example", 1);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore("tasks", { keyPath: "id" });
store.createIndex("byStatusPriorityId", ["status", "priority", "id"]);
};
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function seed(db, rows) {
return new Promise((resolve, reject) => {
const tx = db.transaction("tasks", "readwrite");
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
const store = tx.objectStore("tasks");
rows.forEach(row => store.put(row));
});
}
const db = await openTasks();
try {
await seed(db, [
{ id: "a", status: "open", priority: 1, title: "Indexed" },
{ id: "b", status: "open", title: "Missing priority" }
]);
const counts = await new Promise((resolve, reject) => {
const values = [];
const tx = db.transaction("tasks", "readonly");
tx.oncomplete = () => resolve(values);
tx.onabort = () => reject(tx.error);
const store = tx.objectStore("tasks");
store.count().onsuccess = event => { values[0] = event.target.result; };
store.index("byStatusPriorityId").count().onsuccess = event => { values[1] = event.target.result; };
});
console.log(counts.join(", "));
} finally { db.close(); }Output
2, 1Run 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 or invalid compound key means there is no index entry for that record. The record can still exist in the store. Validate writes and migrations; otherwise an index query can silently omit data that a primary-key read still finds. A unique index enforces uniqueness of indexed keys, not arbitrary business rules or required-field presence.
A cursor exposes both the index key and the primary key
Inspect index keys and stop a cursor after a bounded prefix
async function openTasks() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-course-example", 1);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore("tasks", { keyPath: "id" });
store.createIndex("byStatusPriorityId", ["status", "priority", "id"]);
};
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function seed(db, rows) {
return new Promise((resolve, reject) => {
const tx = db.transaction("tasks", "readwrite");
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
const store = tx.objectStore("tasks");
rows.forEach(row => store.put(row));
});
}
const db = await openTasks();
try {
await seed(db, [
{ id: "b", status: "open", priority: 2, title: "Second" },
{ id: "a", status: "open", priority: 1, title: "First" },
{ id: "c", status: "open", priority: 3, title: "Third" }
]);
const rows = await new Promise((resolve, reject) => {
const result = [];
const tx = db.transaction("tasks", "readonly");
tx.oncomplete = () => resolve(result);
tx.onabort = () => reject(tx.error);
const request = tx.objectStore("tasks").index("byStatusPriorityId").openCursor();
request.onsuccess = () => {
const cursor = request.result;
if (!cursor) return;
result.push([cursor.key, cursor.primaryKey]);
if (result.length < 2) cursor.continue();
};
});
console.log(JSON.stringify(rows));
} finally { db.close(); }Output
[[["open",1,"a"],"a"],[["open",2,"b"],"b"]]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.
cursor.key is the key in the source being traversed; on an index it need not equal cursor.primaryKey. Continue only while another record is needed. Stopping the cursor does not abort the readonly transaction; the operation resolves here on transaction completion. A bounded getAll count is simpler when only values are needed.
Do not insert an unrelated network await between transaction requests and assume the transaction remains active. Web Storage APIs (localStorage, sessionStorage, IndexedDB) owns that lifetime rule. Readonly queries, bounded result collection and explicit completion are separate choices.
Schema upgrades coordinate with open connections
An open older connection can block a requested version upgrade
function open(version, upgrade) {
return new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-upgrade-example", version);
request.onupgradeneeded = () => upgrade?.(request.result);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
const first = await open(1, db => db.createObjectStore("old"));
const events = [];
first.onversionchange = () => events.push("versionchange");
const second = await new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-upgrade-example", 2);
request.onblocked = () => { events.push("blocked"); first.close(); };
request.onupgradeneeded = () => { events.push("upgrade"); request.result.createObjectStore("new"); };
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
console.log(events.join(", "));
console.log(second.version, [...second.objectStoreNames].join(", "));
second.close();Output
versionchange, blocked, upgrade
2 new, oldRun 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 real application should normally respond to versionchange by closing its old connection and coordinating a reload with the user. This example deliberately holds it open until blocked to expose the lifecycle. Raising a version is a migration step, not permission to delete user data. Create stores and indexes inside the upgrade transaction.
An aborted upgrade rolls back its schema changes
const first = await new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-rollback-example", 1);
request.onupgradeneeded = () => request.result.createObjectStore("old");
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
first.close();
const failure = await new Promise(resolve => {
const request = indexedDB.open("indexeddb-rollback-example", 2);
request.onupgradeneeded = () => {
request.result.createObjectStore("temporary");
request.transaction.abort();
};
request.onerror = () => resolve(request.error.name);
});
const restored = await new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-rollback-example");
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
console.log(failure, restored.version, [...restored.objectStoreNames].join(", "));
restored.close();Output
AbortError 1 oldRun 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 failed upgrade does not leave half of this new schema installed. Application migrations still need a data transformation plan and tests for the versions actually in use. Storage may be unavailable, quota-limited, cleared or evicted; a browser database is not a substitute for a backup or synchronization policy.
Guided exercise: construct a bounded query plan
Complete the literal hints. This editor exercise validates query parameters; the database panels above and below execute the actual index operations.
function plan(maxPriority, limit) {
if (!Number.isInteger(maxPriority) || maxPriority < 0 || maxPriority > 9) throw new RangeError("priority");
if (!Number.isInteger(limit) || limit < 1 || limit > ___) throw new RangeError("limit"); // 👉 replace ___ with 20
return { lower: ["open", ___], upper: ["open", maxPriority, "\uffff"], limit }; // 👉 replace ___ with 0
}
console.log(JSON.stringify(plan(___, 3).lower)); // 👉 replace ___ with 2
console.log(plan(2, 3).limit);
// ✅ Expected output:
// ["open",0]
// 3Brief: return a bounded, validated open-task query
Implement planTaskQuery(maxPriority, limit) and async readOpenTasks(db, maxPriority, limit). Accept integer priority 0–9 and row limit 1–20, rejecting invalid parameters before opening a transaction. Use the tasks store and byStatusPriorityId index from the checked fixture. Read open tasks through the inclusive priority bound, in index order, stopping at the row limit.
Resolve only after transaction completion. Select fresh records containing id, priority and trimmed title. For every returned row, require an ID of 1–12 lowercase ASCII letters, open status, an integer priority in range and a title trimmed to 1–80 UTF-16 code units. Abort and reject with TypeError("invalid stored task") if an encountered row is malformed. Propagate transaction failures. Do not close the caller-owned database connection.
function planTaskQuery(maxPriority, limit) {
if (!Number.isInteger(maxPriority) || maxPriority < 0 || maxPriority > 9) throw new RangeError("invalid priority limit");
if (!Number.isInteger(limit) || limit < 1 || limit > 20) throw new RangeError("invalid row limit");
return { lower: ["open", 0], upper: ["open", maxPriority, "\uffff"], limit };
}
console.log(JSON.stringify(planTaskQuery(2, 3).lower));
console.log(planTaskQuery(2, 3).limit);
try { planTaskQuery(2, 0); } catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// ["open",0]
// 3
// RangeError invalid row limitRun the complete bounded query against real IndexedDB
async function openTasks() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("indexeddb-course-example", 1);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore("tasks", { keyPath: "id" });
store.createIndex("byStatusPriorityId", ["status", "priority", "id"]);
};
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
async function seed(db, rows) {
return new Promise((resolve, reject) => {
const tx = db.transaction("tasks", "readwrite");
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
const store = tx.objectStore("tasks");
rows.forEach(row => store.put(row));
});
}
function planTaskQuery(maxPriority, limit) {
if (!Number.isInteger(maxPriority) || maxPriority < 0 || maxPriority > 9) throw new RangeError("invalid priority limit");
if (!Number.isInteger(limit) || limit < 1 || limit > 20) throw new RangeError("invalid row limit");
return { lower: ["open", 0], upper: ["open", maxPriority, "\uffff"], limit };
}
async function readOpenTasks(db, maxPriority, limit) {
const plan = planTaskQuery(maxPriority, limit);
if (!(db instanceof IDBDatabase)) throw new TypeError("database required");
return new Promise((resolve, reject) => {
const rows = [];
let failure = null;
const tx = db.transaction("tasks", "readonly");
tx.oncomplete = () => resolve(rows);
tx.onabort = () => reject(failure || tx.error || new Error("transaction aborted"));
const range = IDBKeyRange.bound(plan.lower, plan.upper);
const request = tx.objectStore("tasks").index("byStatusPriorityId").openCursor(range);
request.onsuccess = () => {
const cursor = request.result;
if (!cursor) return;
const row = cursor.value;
if (!row || typeof row.id !== "string" || !/^[a-z]{1,12}$/.test(row.id) ||
row.status !== "open" || !Number.isInteger(row.priority) ||
row.priority < 0 || row.priority > maxPriority ||
typeof row.title !== "string" || row.title.trim().length < 1 || row.title.trim().length > 80) {
failure = new TypeError("invalid stored task");
tx.abort();
return;
}
rows.push({ id: row.id, priority: row.priority, title: row.title.trim() });
if (rows.length < plan.limit) cursor.continue();
};
});
}
const db = await openTasks();
try {
await seed(db, [
{ id: "z", status: "open", priority: 2, title: " Last " },
{ id: "a", status: "open", priority: 2, title: " First " },
{ id: "c", status: "open", priority: 1, title: " Earlier " },
{ id: "b", status: "closed", priority: 0, title: "Excluded" }
]);
console.log(JSON.stringify(await readOpenTasks(db, 2, 2)));
await seed(db, [{ id: "bad", status: "open", priority: 0, title: "" }]);
try { await readOpenTasks(db, 2, 20); }
catch (error) { console.log(error.name, error.message); }
} finally { db.close(); }Output
[{"id":"c","priority":1,"title":"Earlier"},{"id":"a","priority":2,"title":"First"}]
TypeError invalid stored taskRun 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 result limit bounds this query’s materialized rows. It does not certify the whole database: malformed records outside the range or beyond the limit are not examined. Write validation and migrations remain necessary.
Practice quiz
What does this complete program print? const plan={lower:["open",0],upper:["open",2,"\uffff"],limit:3};console.log(plan.lower[0],plan.limit);
- open 3
- closed 3
- open 2
- open 0
Answer: open 3. The planner explicitly selects the open status and a three-row cap.
On an index cursor, what does primaryKey identify?
- The current array position
- The record’s key in the underlying object store
- The database version
- The index name
Answer: The record’s key in the underlying object store. The index key and object-store primary key are separate values.
What does this complete program print? function valid(n){return Number.isInteger(n)&&n>=1&&n<=20;}console.log(valid(0),valid(20));
- true true
- false false
- false true
- true false
Answer: false true. The bounded row-limit contract excludes zero and includes twenty.
A record is missing one field used by a compound index. What can happen?
- The whole database is deleted
- The store automatically fills the missing field
- Every query throws
- The record remains stored but has no entry in that index
Answer: The record remains stored but has no entry in that index. Index membership depends on obtaining a valid index key.
What does this complete program print? const rows=[{id:"a",title:" First "}];const result=rows.map(x=>({id:x.id,title:x.title.trim()}));console.log(result[0]===rows[0],result[0].title);
- false First
- true First
- false First
- true First
Answer: false First. Selecting and trimming fields creates a fresh result record.
Why should a query resolve on transaction completion?
- A request has no result before then
- A successful request alone does not establish the transaction’s final outcome
- Completion makes the data immune to eviction
- It closes every other tab
Answer: A successful request alone does not establish the transaction’s final outcome. A later failure can still abort a transaction after a request succeeds.
What does this complete program print? function plan(n){if(!Number.isInteger(n)||n<0||n>9)throw new RangeError("priority");return n;}try{console.log(plan("2"));}catch(e){console.log(e.name,e.message);}
- 2
- TypeError priority
- RangeError priority
- undefined
Answer: RangeError priority. The parameter contract rejects numeric strings without coercion.
What should an older connection normally do on versionchange?
- Keep the upgrade blocked forever
- Delete all data immediately
- Ignore every newer schema
- Close and coordinate the application’s reload or update
Answer: Close and coordinate the application’s reload or update. Closing allows the upgrade to proceed while the application handles its state deliberately.
Continue this course
- Previous: MutationObserver (Watching the DOM)
- Next: The Canvas API — Draw shapes, paths, text and animations on a 2D canvas
- Quick reference: JavaScript cheat sheet