JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 14: State and PersistenceLesson 70 of 150About 50 minutes

Lesson 70: IndexedDB fundamentals

01Opening question

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.

const open = indexedDB.open("notes-db", 1);
open.onupgradeneeded = () => {
  open.result.createObjectStore("notes", { keyPath: "id" });
};
open.onsuccess = () => {
  const db = open.result;
  const tx = db.transaction("notes", "readwrite");
  tx.objectStore("notes").put({ id: 1, text: "Buy milk" });
  tx.oncomplete = () => {
    const get = db.transaction("notes").objectStore("notes").get(1);
    get.onsuccess = () => console.log(get.result.text);
  };
};

03Objective and prerequisites

Learning objective: Open an IndexedDB database, create object stores and indexes, and add, read, query and delete records inside transactions, wrapped in promises.

You need: Lesson 69: JSON serialization, Lesson 56: Event listeners

Skills practised: Browser storage, IndexedDB.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

IndexedDB data explorer. Open a sample database, run add, get, index and delete requests, and watch each store's records and each request's events.

Loading the interactive object…

Open the full IndexedDB data explorer page with its guided experiment.

07Examples

ex-070-01Open, create and write Browser page (sandboxed preview)

onupgradeneeded creates the store; a readwrite transaction adds records.

const request = indexedDB.open("notes-db", 1);
request.onupgradeneeded = () => {
  const db = request.result;
  db.createObjectStore("notes", { keyPath: "id", autoIncrement: true });
  console.log("upgrade: created notes store");
};
request.onsuccess = () => {
  const db = request.result;
  const tx = db.transaction("notes", "readwrite");
  const store = tx.objectStore("notes");
  store.add({ text: "Buy milk" });
  store.add({ text: "Call Sam" });
  tx.oncomplete = () => {
    const count = db.transaction("notes").objectStore("notes").count();
    count.onsuccess = () => console.log("notes:", count.result);
  };
};
Sample input
None
Expected output
upgrade: created notes store notes: 2
Common mistake
Trying to create a store in onsuccess; structure changes only work in onupgradeneeded.
Try this
Read every note with getAll and log their texts.
Source
examples/ex-070-01-open-and-put.js

ex-070-02Wrapping requests in promises Browser page (sandboxed preview)

A tiny helper turns requests into promises so async/await works.

const done = (request) => new Promise((resolve, reject) => {
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);
});
function openDB() {
  const request = indexedDB.open("shop", 1);
  request.onupgradeneeded = () => request.result.createObjectStore("products", { keyPath: "sku" });
  return done(request);
}
async function main() {
  const db = await openDB();
  const store = () => db.transaction("products", "readwrite").objectStore("products");
  await done(store().put({ sku: "L1", name: "Lamp", price: 30 }));
  await done(store().put({ sku: "M2", name: "Mug", price: 8 }));
  const lamp = await done(store().get("L1"));
  const all = await done(store().getAll());
  console.log(lamp.name, all.length);
}
main();
Sample input
None
Expected output
Lamp 2
Common mistake
Nesting onsuccess handlers many levels deep instead of using a promise wrapper.
Try this
Add a remove(sku) function using delete.
Source
examples/ex-070-02-promise-wrapper.js

ex-070-03Querying by an index Browser page (sandboxed preview)

An index finds records by a property other than the key.

const done = (r) => new Promise((ok, fail) => { r.onsuccess = () => ok(r.result); r.onerror = () => fail(r.error); });
async function main() {
  const open = indexedDB.open("library", 1);
  open.onupgradeneeded = () => {
    const store = open.result.createObjectStore("books", { keyPath: "id" });
    store.createIndex("byGenre", "genre");
  };
  const db = await done(open);
  const tx = db.transaction("books", "readwrite");
  const books = tx.objectStore("books");
  books.put({ id: 1, title: "Dune", genre: "sci-fi" });
  books.put({ id: 2, title: "Emma", genre: "classic" });
  books.put({ id: 3, title: "Solaris", genre: "sci-fi" });
  const sciFi = await done(books.index("byGenre").getAll("sci-fi"));
  console.log(sciFi.map((b) => b.title).join(", "));
}
main();
Sample input
None
Expected output
Dune, Solaris
Common mistake
Loading every record with getAll and filtering in JavaScript when an index would do it.
Try this
Count classic books with index("byGenre").count("classic").
Source
examples/ex-070-03-index-query.js

ex-070-04Read-only means read-only Browser page (sandboxed preview)

Writing in a readonly transaction fails with ReadOnlyError.

const open = indexedDB.open("modes", 1);
open.onupgradeneeded = () => open.result.createObjectStore("kv");
open.onsuccess = () => {
  const db = open.result;
  const store = db.transaction("kv").objectStore("kv");
  try {
    store.put("value", "key");
  } catch (error) {
    console.log(error.name);
  }
  const rw = db.transaction("kv", "readwrite").objectStore("kv");
  const put = rw.put("value", "key");
  put.onsuccess = () => console.log("saved with key", put.result);
};
Sample input
None
Expected output
ReadOnlyError saved with key key
Common mistake
Forgetting the "readwrite" mode, because "readonly" is the default.
Try this
Store objects without a keyPath by passing the key as the second argument.
Source
examples/ex-070-04-readonly-error.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The note is not saved

Use the right transaction mode.

let saved = "no";
const open = indexedDB.open("ex-a", 1);
open.onupgradeneeded = () => open.result.createObjectStore("notes", { keyPath: "id" });
open.onsuccess = () => {
  const store = open.result.transaction("notes").objectStore("notes");
  try {
    const put = store.put({ id: 1, text: "Hello" });
    put.onsuccess = () => { saved = "yes"; console.log("saved:", saved); };
  } catch (error) {
    console.log(error.name);
  }
};

Read every record

Read a store with getAll inside oncomplete.

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.

const done = (r) => new Promise((ok, fail) => { r.onsuccess = () => ok(r.result); r.onerror = () => fail(r.error); });
let shown = null;
async function main() {
  const open = indexedDB.open("tasks", 1);
  open.onupgradeneeded = () => open.result.createObjectStore("tasks", { autoIncrement: true });
  const db = await done(open);
  const store = () => db.transaction("tasks", "readwrite").objectStore("tasks");
  const countPromise = done(store().count());
  done(store().add({ title: "Write report" }));
  shown = await countPromise;
  console.log("Tasks: " + shown);
}
main();

More cases in the Debugging Detective Laboratory

11Practical scenario

Offline-first apps

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.

const choose = (size, structured) => size > 1000 || structured ? "IndexedDB" : "localStorage";
console.log(choose(10, false), choose(5000, true));

12Knowledge check

1. When can you create object stores?

  • Any time
  • Only in onupgradeneeded
  • Only in onsuccess
  • Only in a readonly transaction

2. What is the default transaction mode?

  • readwrite
  • readonly
  • versionchange
  • none

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.
  • Wrap requests in promises to use async/await.

16AI learning prompts

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 explanation IndexedDB
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 prediction IndexedDB 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.
Debugging IndexedDB 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 generation IndexedDB 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 review IndexedDB 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.