Learning Tips | Published Nov 17, 2026 | 9 min read

A Practical Guide to IndexedDB Browser Storage

Learn IndexedDB object stores, indexes, schema upgrades, short transactions, offline use, and practical error handling.

Diagram follows a web app opening a versioned IndexedDB database, queuing a request in a short transaction, reading an object store or index, and handling transaction completion

IndexedDB stores structured records in a browser asynchronously, making it useful for offline drafts, cached application data, and larger datasets. Learn how object stores, indexes, version upgrades, and short transactions fit together—and how to handle failures and multiple tabs.

When a web app needs to keep more than a few small preferences on the device, IndexedDB provides a structured, asynchronous database built into the browser. A notes app, for example, could keep draft records available while the network is down and synchronize them later. IndexedDB is a local persistence layer; it does not sync data to a server or provide a backup by itself.

It is a better fit than localStorage for collections of structured records and larger data such as blobs. Its API is asynchronous, so database work does not have to block the main thread while it completes. It is still worth choosing a simpler tool when the data is small: use Web Storage for a small preference, the Cache API for request and response caching, and IndexedDB when you need keyed records, queries, or indexes.

Think in databases, object stores, and indexes

An IndexedDB database has a name and integer version. Inside it, an object store holds records, usually JavaScript objects with a key path such as id. An index provides another lookup path through a record field, such as a date or status. IndexedDB uses structured cloning to store supported values; it does not store arbitrary executable JavaScript objects.

For a simple offline notes feature, a notes store might use id as its primary key and an index on updatedAt to retrieve notes in date order. Decide which lookups the interface needs before adding indexes: every extra index also has to be maintained as records change.

Create or upgrade the schema deliberately

Opening a database with a higher version triggers upgradeneeded. Create or adjust object stores and indexes there, inside the browser's version-change transaction. Keep upgrades incremental: check whether a store or index already exists, and add migrations in order as the schema evolves.

function openNotesDatabase() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("notes-app", 1);

    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      let notes;

      if (!db.objectStoreNames.contains("notes")) {
        notes = db.createObjectStore("notes", { keyPath: "id" });
      } else {
        notes = event.target.transaction.objectStore("notes");
      }

      if (!notes.indexNames.contains("updatedAt")) {
        notes.createIndex("updatedAt", "updatedAt");
      }
    };

    request.onsuccess = () => {
      const db = request.result;
      db.onversionchange = () => db.close();
      resolve(db);
    };

    request.onerror = () => reject(request.error);
    request.onblocked = () => {
      console.warn("Close or reload another tab to finish the database upgrade.");
    };
  });
}

The example uses database version 1 for the first schema. When the schema changes, ship a higher version and update the migration logic. If an older tab still has the database open, the upgrade can be blocked. Close the old connection when its versionchange event fires and provide a useful message when the opening request reports blocked; do not silently leave the user waiting.

Read and write inside short transactions

Every record read or write occurs in a transaction. Use readonly for queries and readwrite for changes. Scope a transaction to only the stores it needs, enqueue its requests promptly, and observe the transaction's completion or failure. An individual request succeeding is not the same as the transaction committing successfully.

function saveNote(db, note) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", "readwrite");
    const request = tx.objectStore("notes").put(note);

    request.onerror = () => reject(request.error);
    tx.oncomplete = () => resolve(note);
    tx.onabort = () => reject(tx.error || new Error("Save was aborted"));
    tx.onerror = () => reject(tx.error || new Error("Save failed"));
  });
}

function getNote(db, id) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction("notes", "readonly");
    const request = tx.objectStore("notes").get(id);

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

put() inserts or replaces a record with the same key; add() instead fails if that key already exists. A read may return undefined when no record matches. Treat database and request errors as normal outcomes, and show a useful fallback rather than assuming a local write can never fail.

Keep transaction work synchronous between requests

IndexedDB requests are asynchronous, but a transaction is intentionally short-lived. Do not start a transaction, wait for unrelated work such as fetch(), and then try to issue a database request: the transaction may already be inactive. Finish network work first, then open a transaction for the database operations. For multi-step request chains, enqueue the next database request from a request event handler or use a well-tested promise wrapper whose transaction semantics are documented.

If several related records must change together, put those writes in one readwrite transaction. The transaction either completes or aborts, which is useful for keeping related local data consistent. Avoid holding a transaction open while waiting on user interaction or other asynchronous APIs.

Plan for quota, privacy, and offline behavior

  • Handle storage errors: browsers set origin storage limits and may evict data under pressure. A local database is not a guaranteed backup; let users export important work or sync it to a server when appropriate.
  • Keep sensitive data out: same-origin scripts can access an app's IndexedDB. Do not treat it as a secure vault for passwords, access tokens, or other secrets. Protect against cross-site scripting and minimize stored personal data.
  • Feature-detect: check that indexedDB is available and handle open, request, and transaction errors. Keep the interface usable when persistence is unavailable.
  • Design offline states: IndexedDB can hold application records, but it does not intercept network requests. Pair it with a service worker and the Cache API when the app also needs offline HTML, scripts, or network responses.
  • Test upgrades and multiple tabs: try first install, each schema migration, blocked upgrades, failed writes, and reloads. Close database connections when the app no longer needs them.

A practical decision checklist

Before adding IndexedDB, list the records, their keys, the queries the UI needs, and the data that must survive a reload. Add indexes only for real query paths. Version schema changes, make transaction scopes small, and make errors visible. Then test realistic data volumes and offline transitions in the browsers your users rely on.

These habits keep client-side storage maintainable: choose a tool that matches the data, keep migrations explicit, and never confuse browser persistence with server synchronization or durable backup.

Further reading

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance