liveBook · Manning

IndexedDB

As explained in Vanilla Web

IndexedDB is a browser database API for storing and querying structured data, including data larger than typical web-storage values.

Choose storage by data shape: use IndexedDB for structured application data such as saved drafts, offline records, sync queues, and user-generated content. It is a browser-native database, not simply a larger localStorage. section 12.4.5

An IndexedDB database contains object stores, which hold JavaScript values rather than rows in a fixed relational schema. Records use explicit keys, key paths, or generated keys; indexes support lookups beyond the primary key. Reads and writes run through asynchronous transactions. section 12.4.5

Opening a database with a newer version triggers an upgrade step for creating or changing stores and indexes. Use that step to migrate local data as the schema evolves. The raw API is verbose; Promise wrappers such as idb can reduce the ceremony. section 12.4.5

Plan for quota limits and eviction: synchronize or provide recovery for important data, and keep critical copies server-side. Structured cloning supports richer values than JSON strings, but large objects still cost time to clone; favor reasonably small records and index common lookups. section 2.4.3 section 12.4.5

Listing 12.5 Opening a small IndexedDB database
function requestToPromise(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

async function openDatabase() {
  const request = indexedDB.open("vanilla-web", 1);

  request.onupgradeneeded = (event) => {
    const db = request.result;
    if (event.oldVersion < 1) {
      db.createObjectStore("drafts", { keyPath: "id" });
    }
  };

  request.onblocked = () => {
    console.warn(
      "Another tab blocks IndexedDB upgrade; close other tabs to continue."
    );
  };

  return requestToPromise(request);
}

Inspect the native database-opening and upgrade flow, including a keyPath store and a warning when another tab blocks an upgrade. section 12.4.5

How Vanilla Web covers it

How deep it goes
Defines keys, stores, indexes, transactions, and versioned upgrades, then demonstrates database operations through native APIs and idb.
Examples
Uses saved drafts with a keyPath and demonstrates adding, updating, retrieving, counting, and deleting records.
What you can do after
Build it from scratch with native database opening and upgrade logic, or apply it through the idb Promise wrapper.
How it connects
Connects object stores and indexes with transactions, schema migrations, structured cloning, and browser storage choices.

Also explained in

Compare how 2 books explain IndexedDB →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.