localStorage is perfect for a theme setting. What about ten thousand notes, searched by tag, that must work offline?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
IndexedDB is a database in the browser. Everything is asynchronous: you make requests and handle their success events. In this sandbox a memory-only stand-in with the same API runs your code; the downloaded files use your browser's real IndexedDB.
Learning objective: Open an IndexedDB database, create object stores and indexes, and add, read, query and delete records inside transactions, wrapped in promises.
IndexedDB is a database built into the browser. It stores objects (not just strings), handles large amounts of data, and works offline.
A database contains object stores (like tables). Each record has a key, either a property named by keyPath or a number generated with autoIncrement.
All reads and writes happen inside a transaction: db.transaction("notes", "readwrite"). Read-only work uses "readonly", which is the default.
Operations are asynchronous requests. You attach onsuccess and onerror handlers, like event listeners. The advanced examples wrap requests in promises so they can use await; Lessons 78 and 79 explain promises fully, and here the small helper is given to you.
Structure changes (new stores and indexes) are only allowed in onupgradeneeded, which runs when you open the database with a higher version number. Plan versions like migrations.
An index lets you look records up by another property (createIndex("byTag", "tag")) without scanning everything.
Transactions commit automatically when there are no pending requests. Awaiting something unrelated (like fetch) inside a transaction lets it finish early and later requests fail with TransactionInactiveError.
Most apps use a small promise wrapper (such as the idb library) around this API. Browsers may evict data under storage pressure unless you request persistent storage with navigator.storage.persist().
05Definitions
IndexedDB
A browser database for storing large amounts of structured data, accessed asynchronously.
Object store
A named collection of records in an IndexedDB database, similar to a table.
keyPath
The property of each record used as its unique key.
Transaction
A group of database operations on chosen stores that succeed or fail together.
Index
A secondary lookup on a record property, used to query by that property.
const open = indexedDB.open("ex-b", 1);
open.onupgradeneeded = () => open.result.createObjectStore("cities", { keyPath: "name" });
open.onsuccess = () => {
const db = open.result;
const tx = db.transaction("cities", "readwrite");
const store = tx.objectStore("cities");
store.put({ name: "Lima", pop: 10 });
store.put({ name: "Oslo", pop: 1 });
store.put({ name: "Accra", pop: 3 });
tx.oncomplete = () => {
// TODO: read every city with getAll and, in its onsuccess, log the
// names joined with ", " (records come back in key order)
};
};
A notes repository
Hide IndexedDB behind a small async API.
// Advanced (previews Lessons 78-79). You may use this helper:
const done = (r) => new Promise((ok, fail) => { r.onsuccess = () => ok(r.result); r.onerror = () => fail(r.error); });
// Write createNotesRepo() -> Promise of { add(note), byTag(tag), remove(id) }
// Database "repo", version 1, store "notes" (keyPath "id", autoIncrement)
// with an index "byTag" on "tag". add resolves with the new id.
// Then: add three notes (two tagged "work"), log the texts tagged "work"
// joined with ", ", remove the first work note, and log the count again.
09Prediction
Commit to an answer first, then run the real code to compare.
const open = indexedDB.open("p", 1);
open.onupgradeneeded = () => open.result.createObjectStore("s", { autoIncrement: true });
open.onsuccess = () => {
const store = open.result.transaction("s", "readwrite").objectStore("s");
const a = store.add("x");
const b = store.add("y");
b.onsuccess = () => console.log(a.result, b.result);
};
console.log("opening");
What is printed?
10Debugging investigation
The count is always one behind
After saving a task, the app shows the number of tasks, but the number never includes the task that was just saved.
A field-inspection app stores thousands of inspection records and photos in IndexedDB so inspectors can work without signal. When the connection returns, a sync step uploads new records. Settings such as the theme still use localStorage.
3. A request's onsuccess logs "A", and the next line after the request logs "B". What order appears?
A B
B A
A only
B only
4. Why does the second request fail with TransactionInactiveError?
const store = db.transaction("s", "readwrite").objectStore("s");
const data = await fetch(url).then((r) => r.json());
store.put(data);
The transaction committed while awaiting the network
put is not allowed
The store name is wrong
await is not allowed
5. What does an index let you do?
Encrypt records
Look up records by a property other than the key
Increase storage quota
Sort strings
6. An app stores 20,000 product records for offline search. Which storage fits?
localStorage with one JSON string
IndexedDB with an index on the search field
Cookies
sessionStorage
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
The note is not saved: Prints saved: yes; Uses readwrite
Read every record: Prints the cities in key order; Uses getAll
A notes repository: Prints the work notes, then 1; Uses an index
The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-14-state-and-persistence/lesson-070-indexeddb-fundamentals/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
IndexedDB stores structured data in the browser, asynchronously.
Stores and indexes are created in onupgradeneeded.
All work happens in transactions; readwrite must be requested.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationIndexedDB
Context: I am learning IndexedDB in JavaScript.
Task: Explain IndexedDB databases, object stores, transactions and indexes with a small notes example.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionIndexedDB drill
Context: I have practised IndexedDB.
Task: Give me six IndexedDB snippets and ask what each logs and in which order.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
DebuggingIndexedDB bug
Context: My IndexedDB put throws ReadOnlyError.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationIndexedDB practice
Context: I finished the IndexedDB exercises.
Task: Create three IndexedDB exercises using a promise wrapper, with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewIndexedDB review
Context: Here is my code that uses IndexedDB.
Task: Review my IndexedDB code for transaction mistakes and missing error handling.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.