Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Offline and Background Sync

Offline Data with IndexedDB

Store app data offline with IndexedDB: object stores, keys, indexes, transactions, versioned upgrades and a promise wrapper, with a runnable in-memory stand-in.

The Cache Storage API stores responses: whole HTTP requests and their bodies. That is perfect for pages, scripts and images, but awkward for application data such as notes, to-do items or a shopping cart. For that you want a database in the browser. The one every browser ships is IndexedDB: an asynchronous, transactional, key-value store that holds structured data (objects, arrays, dates, blobs) and can handle hundreds of megabytes.

IndexedDB is available in pages, in web workers and, importantly, in service workers. That last point is what makes it the backbone of offline sync, because the worker can read and write the same data your page uses.

The interactive previews in this tutorial run in an opaque-origin sandbox where IndexedDB is not available. The real API is shown in read-only blocks. The runnable blocks use a small in-memory object store with the same shape, so you can practice the logic.

The vocabulary

Term Meaning
Database A named, versioned container. One origin can have many.
Object store Like a table. Holds records (JavaScript values) addressed by key.
Key Primary identifier: a keyPath property, or an auto-incremented number.
Index An extra lookup path on a property, for example by-updated.
Transaction A group of reads and writes that succeeds or fails as a whole.
Version An integer. Raising it fires upgradeneeded, the only place to change the schema.

Opening a database and creating stores

You open a database by name and version. The first time, or when the version is higher than what is stored, upgradeneeded fires and you create stores and indexes.

JavaScript
// read-only: the raw API
function openDb() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("notes-app", 2);

    request.onupgradeneeded = (event) => {
      const db = request.result;
      if (event.oldVersion < 1) {
        const notes = db.createObjectStore("notes", { keyPath: "id" });
        notes.createIndex("by-updated", "updatedAt");
      }
      if (event.oldVersion < 2) {
        db.createObjectStore("outbox", { keyPath: "seq", autoIncrement: true });
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

The oldVersion checks are the standard migration pattern: each step runs only for databases that have not seen it yet, so users upgrading from any earlier version end up with the same schema.

Reading and writing

Everything happens inside a transaction on one or more stores. Use "readonly" when you can, because read-only transactions run in parallel.

JavaScript
function put(db, storeName, value) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction(storeName, "readwrite");
    tx.objectStore(storeName).put(value);
    tx.oncomplete = () => resolve();
    tx.onerror = () => reject(tx.error);
  });
}

function getAll(db, storeName) {
  return new Promise((resolve, reject) => {
    const request = db.transaction(storeName).objectStore(storeName).getAll();
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

Resolve on tx.oncomplete, not on the request's onsuccess: only the transaction event guarantees the data is committed. A transaction also closes itself when control returns to the event loop with no pending requests, so never await something unrelated (like a fetch) in the middle of one.

Try it: an in-memory store with the same shape

The following object store exposes put, get, getAll, delete and an index lookup, using promises. Swapping it for real IndexedDB means changing only the inside of these functions.

JS A tiny notes store

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

No output.

structuredClone mirrors what IndexedDB does: values are copied using the structured clone algorithm, so you get plain data back, never the same object reference, and functions or DOM nodes cannot be stored.

Indexes and ranges

An index lets you query without scanning everything. With the real API you pass a IDBKeyRange:

JavaScript
const index = db.transaction("notes").objectStore("notes").index("by-updated");
const recent = index.getAll(IDBKeyRange.lowerBound(Date.now() - 86_400_000));

Ranges can be lowerBound, upperBound, bound or only. Cursors (openCursor) walk records one by one and are useful for large sets, but getAll with a range is shorter and often faster.

Do not write the raw API forever

The callback style is verbose, so most projects use a small wrapper. The popular idb library turns requests into promises in about 1 KB, and Dexie adds a query layer. Whichever you pick, keep the data layer in one module so the page and the service worker share it:

JavaScript
// db.js, imported by the page and by the service worker (type: "module")
export async function saveNote(note) { /* put into "notes" */ }
export async function listNotes() { /* getAll from "notes" */ }

Request persistent storage for important offline data with navigator.storage.persist(). Without it the browser may evict your data when the device runs low on disk space. navigator.storage.estimate() tells you roughly how much you use and how much you may use.

Try it: a transaction that fails as a whole

Atomicity is the reason to use a database at all. The stand-in below shows the idea: apply a batch of changes to a copy and only commit if every step works.

JS All or nothing

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

No output.

In IndexedDB you get this behavior by calling tx.abort() or by letting an error go unhandled inside the transaction.

Storing what the offline user does

IndexedDB holds two kinds of data in a typical PWA:

  • A local copy of server data (articles, notes) that the page reads while offline.
  • A queue of changes made offline that still need to reach the server. That queue is the subject of the offline outbox pattern, and background sync sends it once the network returns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where may you create object stores and indexes?

    The schema can only change while a version change transaction is running, which is what upgradeneeded provides.
  2. 2. Which event confirms that data is committed?

    A request can succeed and its transaction can still abort later. oncomplete is the commit confirmation.
  3. 3. Why is awaiting a fetch inside an open transaction a bug?

    Transactions close themselves when there are no pending requests; waiting for other async work lets that happen and the next write throws TransactionInactiveError.
  4. 4. What does navigator.storage.persist() ask for?

    Persistent storage is protected from automatic eviction; it does not change speed or sync anything.

Summary

  • Use Cache Storage for responses and IndexedDB for structured application data.
  • Change the schema only in upgradeneeded, step by step on oldVersion.
  • Work inside transactions, and wait for oncomplete before assuming a write is saved.
  • Keep a single data module (or use idb/Dexie) shared by the page and the service worker.
  • Ask for persistent storage when the data matters to the user.

Next: Background Sync