Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 156 ยท Browser APIs

IndexedDB for Client-Side Storage

Store large structured data in the browser with IndexedDB - databases, object stores, indexes, transactions, cursors, upgrades and a small promise wrapper you can reuse.

Web Storage is perfect for small settings, but it stores only strings, blocks the page while it works, and holds a few megabytes at best. What if you are building an offline notes app, a cache of thousands of products, a drawing editor that keeps images, or a mail client that must search messages without the network? For that you need a real database inside the browser.

IndexedDB is that database. It stores JavaScript objects (including files, blobs and dates, not just strings), it can hold hundreds of megabytes or more, it supports indexes for fast lookups, and its operations are asynchronous, so they never freeze the page. It is also famous for an old, clumsy, event-based API. In this lesson you will learn the concepts, read the raw API once, then wrap it in a small promise-based helper that makes it pleasant to use.

IndexedDB is blocked inside the editors on this site. Their sandbox has no real origin, so indexedDB.open() throws a SecurityError. The runnable example below is written the way production code should be: it tries IndexedDB and falls back to an in-memory store with the same interface when the database is not available. Everything labelled "Read-only" works as written in a normal page served from https:// or http://localhost.

The building blocks

IndexedDB has a handful of concepts, and once they are clear the API is easier to read:

  • Database: a named container, bound to your site's origin. It has an integer version.
  • Object store: like a table. It holds records (any structured-clonable JavaScript value). You create stores only during a version upgrade.
  • Key: every record has a unique key. Either it is stored inside the object (a keyPath such as "id"), or the store generates numbers for you (autoIncrement), or you supply the key when you add.
  • Index: a second lookup path over a property, for example "all notes with this tag". Without an index you would have to scan the whole store.
  • Transaction: every read or write happens inside one. A transaction is either readonly or readwrite, and all of its changes succeed together or are rolled back together.
  • Request: each operation returns a request object. You get the result in its onsuccess event or its error in onerror.
flowchart LR
  O["indexedDB.open(name, version)"] --> U{"New or higher version?"}
  U -->|"yes"| UP["upgradeneeded: create stores and indexes"]
  U -->|"no"| S["success: you have the db"]
  UP --> S
  S --> T["db.transaction(stores, mode)"]
  T --> ST["transaction.objectStore(name)"]
  ST --> R["add / put / get / delete / getAll / openCursor"]
  R --> C["transaction complete: changes are saved"]

Open a database, upgrade the schema if needed, then do all work inside transactions.

Opening a database and creating a store

You open a database by name and version. If the database does not exist, or the version you ask for is higher than the stored one, the upgradeneeded event fires first, and that is the only place where you may create or change stores:

JavaScript
// Read-only: runs in a real page
const request = indexedDB.open("notes-app", 1);

request.onupgradeneeded = () => {
  const db = request.result;
  const notes = db.createObjectStore("notes", { keyPath: "id", autoIncrement: true });
  notes.createIndex("byTag", "tag");          // fast lookup by tag
  notes.createIndex("byCreated", "created");  // ordered by date
};

request.onsuccess = () => {
  const db = request.result;
  console.log("Opened", db.name, "version", db.version);
};

request.onerror = () => console.error("Could not open:", request.error);

keyPath: "id" with autoIncrement: true means: the object's id property is its key, and the store invents one if the object has none. To change the schema later (a new store, a new index), open the database with version 2, and in upgradeneeded check event.oldVersion to apply only the missing steps, exactly like database migrations on a server.

Reading and writing with transactions

Every operation needs a transaction on the stores it touches:

JavaScript
// Read-only
const tx = db.transaction("notes", "readwrite");
const store = tx.objectStore("notes");

store.add({ title: "Buy milk", tag: "home", created: Date.now() });   // fails if the key exists
store.put({ id: 1, title: "Buy oat milk", tag: "home", created: Date.now() }); // insert or replace

tx.oncomplete = () => console.log("Saved");
tx.onerror = () => console.error("Failed:", tx.error);

The most important methods on a store:

Method What it does
add(value[, key]) Insert a new record; errors if the key is already used
put(value[, key]) Insert, or replace if the key exists
get(key) One record, or undefined
getAll([query][, count]) An array of records
getAllKeys() / count() The keys, or how many there are
delete(key) / clear() Remove one record, or all records
index(name).get(value) / .getAll(value) Look up by an index
openCursor() Walk through records one at a time

Remember that the transaction, not the request, tells you data is safe: wait for tx.oncomplete before you assume the write is stored.

The transaction auto-commit trap

A transaction stays open only while there are pending requests and your code is running right after their callbacks. If you await something unrelated (a fetch(), a timer) in the middle, the transaction finishes by itself and your next request fails with TransactionInactiveError:

JavaScript
// Read-only: this is a bug
const tx = db.transaction("notes", "readwrite");
const store = tx.objectStore("notes");
const note = await fetch("/api/note/1").then((r) => r.json()); // the transaction ends here
store.put(note);   // TransactionInactiveError

The fix is simple: do the slow work first, then open the transaction and issue all its requests together.

From events to promises

IndexedDB predates promises, so every request uses events. A tiny helper converts any request into a promise, and a second helper runs one operation in its own transaction and resolves when the transaction completes:

JavaScript
// Read-only: runs in a real page
function promisify(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

function run(db, mode, fn) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", mode);
    const request = fn(tx.objectStore("notes"));
    tx.oncomplete = () => resolve(request.result);
    tx.onerror = () => reject(tx.error);
    tx.onabort = () => reject(tx.error);
  });
}

Now await run(db, "readonly", (s) => s.get(1)) reads like ordinary code. (The popular idb library is essentially this idea, polished. If you use IndexedDB heavily, adopt it rather than reinventing it.)

A notes store that falls back to memory

Here is the whole thing assembled: a createNoteStore() function that opens IndexedDB, creates the store and an index, and returns small add, get, byTag, all and remove methods. If IndexedDB is unavailable (as in this sandbox, or in some private-browsing modes), it quietly uses a Map with the same methods, so the rest of the app never needs to know. Run it and look at which store you got:

JS A note store with an in-memory fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The two stores expose identical methods, so callers cannot tell them apart. This "adapter" shape also makes the code easy to test: your unit tests can use the memory version while the app uses the real database.

Indexes, key ranges and cursors

An index is how you query by something other than the primary key. index.getAll("js") returns every note whose tag is "js". Add { unique: true } to createIndex() to forbid duplicates (an email address, say).

For ranges, use IDBKeyRange:

JavaScript
// Read-only
const lastWeek = Date.now() - 7 * 24 * 60 * 60 * 1000;
const recent = await promisify(
  db.transaction("notes").objectStore("notes").index("byCreated")
    .getAll(IDBKeyRange.lowerBound(lastWeek)),
);
// Other builders: upperBound(x), bound(a, b), only(x), plus open/closed variants

When a store is huge and you do not want everything in memory at once, use a cursor, which visits one record at a time in key order:

JavaScript
// Read-only
const tx = db.transaction("notes");
const request = tx.objectStore("notes").openCursor();

request.onsuccess = () => {
  const cursor = request.result;
  if (!cursor) return console.log("Done");   // no more records
  console.log(cursor.key, cursor.value.title);
  cursor.continue();                         // move to the next record
};

Pass "prev" as the direction to walk backwards, and use cursor.update(newValue) or cursor.delete() to change the record you are standing on.

Practical advice

  • Version every schema change. Never edit a store without bumping the version; handle each old version in upgradeneeded.
  • Keep transactions short and do not await unrelated work inside them.
  • Handle blocked upgrades. If another tab holds an older connection open, your upgrade waits and fires a blocked event. Close connections when you receive versionchange: db.onversionchange = () => db.close();.
  • Quota and eviction. Browsers store site data in a shared quota. navigator.storage.estimate() reports usage, and navigator.storage.persist() asks the browser not to evict your data under pressure.
  • Do not store secrets. IndexedDB is readable by any script on your origin, like localStorage; a single cross-site scripting hole exposes it. See Security.
  • It also works in workers, so you can read and write a large database off the main thread (see Web Workers).
  • Choose the right tool. Use localStorage for tiny settings, cookies for what the server must see on every request, the Cache API for HTTP responses, and IndexedDB for structured or large data you want to query.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When are you allowed to create or delete object stores?

    Schema changes can only happen during a version change transaction, which is opened by the upgradeneeded event.
  2. 2. What is the difference between add() and put()?

    add() raises a ConstraintError for a duplicate key; put() overwrites an existing record.
  3. 3. Why does a request fail with TransactionInactiveError after you await a fetch() in the middle?

    A transaction closes automatically when control returns to the event loop with no pending requests. Do slow async work before opening the transaction.
  4. 4. What is an index used for?

    An index such as byTag lets you query records by that property without scanning the entire store.
  5. 5. Why does the lesson's note store fall back to a Map?

    Storage can fail or be blocked. An adapter with the same interface lets the rest of the app run unchanged.

Summary

  • IndexedDB is an asynchronous, transactional database for large, structured data in the browser, including blobs and files.
  • Open a database with a name and version; create object stores and indexes in upgradeneeded.
  • Do all work inside transactions (readonly or readwrite); the transaction's complete event means the data is saved.
  • Do not await unrelated async work inside a transaction.
  • Wrap requests in promises (or use the idb library); use indexes, key ranges and cursors for queries.
  • Plan for blocked or unavailable storage with a fallback, and never keep secrets there.

Next, go back to strings and learn a powerful feature of template literals: Tagged Template Literals.