Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IndexedDB: onupgradeneeded and the upgrade transaction

Change an IndexedDB schema in `onupgradeneeded`, get the upgrade transaction from `request.transaction`, and wait for `success` before using the new schema.

Version: Current web platform; runtime support varies

Syntax

// The upgrade lifecycle is defined by IndexedDB, not by an ECMAScript edition.
const request = indexedDB.open(name, version);
request.onupgradeneeded = (event) => {
  const db = request.result;
  const tx = request.transaction;
  // Apply schema changes through db and tx while tx is active.
};

IDBOpenDBRequest.onupgradeneeded/transaction pairs an event handler property with the request's transaction property. indexedDB.open(name, version) immediately returns an IDBOpenDBRequest and opens the database asynchronously. upgradeneeded fires when creating a database or opening it at a higher version. The same version does not trigger it; a lower version fails with VersionError. IndexedDB is a Web API, not an ECMAScript 2024 feature.

Inside the handler, request.result is the IDBDatabase connection. The read-only request.transaction property, inherited from IDBRequest, holds the IDBTransaction that IndexedDB automatically creates in "versionchange" mode. The property is null immediately after open() and again at success. db.transaction() starts a separate "readonly" or "readwrite" transaction, not an upgrade transaction.

Use event.oldVersion and event.newVersion to select migration steps. A fresh database starts at oldVersion 0; separate version checks let several steps run when versions are skipped. Create a store with db.createObjectStore() and add an index to an existing store with tx.objectStore(name).createIndex(). You can also migrate records in the same transaction.

Queue work while the transaction is active: directly in the upgradeneeded handler or in event handlers for its requests. Do not assume it stays active across await fetch() or a timer. Calling tx.abort() rolls back schema, data, and version changes, and the open request fires error instead of success. If the transaction commits, its complete event comes before the open request's success.

An existing connection, such as one in another tab, can hold up the upgrade. Handle blocked on the open request, and close existing connections with db.close() in their versionchange handlers.

Examples

<!doctype html>
<meta charset="utf-8">
<title>IndexedDB upgrade transaction</title>
<script>
(() => {
  const name = `cktis-indexeddb-${crypto.randomUUID()}`;
  const reportError = (event) => console.error(event.target.error);

  function openVersion(version) {
    const request = indexedDB.open(name, version);
    request.onerror = reportError;
    request.onupgradeneeded = ({ oldVersion, newVersion }) => {
      const db = request.result;
      const tx = request.transaction;
      if (oldVersion < 1) db.createObjectStore("books", { keyPath: "id" });
      if (oldVersion < 2 && newVersion >= 2) {
        console.log(`upgrade: ${oldVersion} -> ${newVersion} (${tx.mode})`);
        tx.objectStore("books").createIndex("by_title", "title");
        tx.oncomplete = () => console.log("complete");
      }
    };
    return request;
  }

  const first = openVersion(1);
  first.onsuccess = () => {
    first.result.close();
    const second = openVersion(2);
    console.log(`before: ${second.transaction}`);
    second.onsuccess = () => {
      const db = second.result;
      const store = db.transaction("books", "readonly").objectStore("books");
      console.log(`success: ${second.transaction}; index: ${store.indexNames.contains("by_title")}`);
      db.close();
      indexedDB.deleteDatabase(name).onerror = reportError;
    };
  };
})();
</script>

Result

before: null
upgrade: 1 -> 2 (versionchange)
complete
success: null; index: true

Open the HTML page in a browser in a secure context with access to IndexedDB and `crypto.randomUUID()`. View the output in the developer console. The example creates a randomly named database at version 1, closes that connection, adds `by_title` at version 2, and requests deletion of the test database after checking the index.

Related lessons

  • JavaScript · Lesson 31 · Advanced · Version: 4

Sources