Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

IDBTransaction — an IndexedDB transaction

IDBTransaction groups IndexedDB operations so that changes commit together or roll back. Learn about object-store scope, the complete event, cancellation with abort(), and the error property.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const tx = db.transaction("items", "readwrite");
const store = tx.objectStore("items");
tx.addEventListener("complete", () => {});
tx.addEventListener("abort", () => { console.error(tx.error); });
// To cancel before committing: tx.abort();

IDBTransaction groups IndexedDB operations atomically: all changes commit or roll back. db.transaction() specifies the object-store scope and mode: readonly for reading, readwrite for writing as well. This is a Web API, not part of ECMAScript; Node 24 does not establish browser availability. Check for indexedDB in the target environment.

IDBTransaction.objectStore(name) returns a handle to a store within the transaction's scope; another name causes NotFoundError. Queue operations while the transaction is active, usually immediately after creation or in its request event handlers. Waiting for unrelated asynchronous work can allow the transaction to finish automatically.

IDBTransaction.complete denotes the complete event, handled through oncomplete or addEventListener, not a method. It confirms commitment; an individual request's success does not guarantee this. IDBTransaction.abort() rolls back changes and leads to an abort event; calling it while committing or after finishing throws InvalidStateError.

IDBTransaction.error is a property containing a DOMException describing the failure, or null, including after a manual abort(). Do not confuse it with the error event: request errors can bubble to the transaction.

If the database opens and the operations proceed as intended, the code writes 42 under the key "answer" and waits for complete to confirm the commit. It then aborts a separate transaction that writes 99, reads back the retained value 42, and logs it. In the displayed run, opening the database fails with SecurityError before any transaction starts. The output Transaction not started: SecurityError therefore shows neither a write nor a commit.

Examples

(async () => {
  const name = `cktis-transaction-${crypto.getRandomValues(new Uint32Array(4)).join('-')}`;
  const result = request => new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
  const completed = tx => new Promise((resolve, reject) => {
    tx.oncomplete = resolve;
    tx.onabort = () => reject(tx.error ?? new DOMException('Transaction aborted', 'AbortError'));
  });

  let db;
  try {
    const open = indexedDB.open(name, 1);
    open.onupgradeneeded = () => open.result.createObjectStore('items');
    db = await result(open);

    const write = db.transaction('items', 'readwrite');
    const scope = Array.from(write.objectStoreNames).join(', ');
    const committed = completed(write);
    write.objectStore('items').put(42, 'answer');
    await committed;

    const undo = db.transaction('items', 'readwrite');
    const aborted = new Promise((resolve, reject) => {
      undo.onabort = () => resolve(undo.error);
      undo.oncomplete = () => reject(new Error('Expected an abort'));
    });
    const update = undo.objectStore('items').put(99, 'answer');
    update.onsuccess = () => undo.abort();
    const abortError = await aborted;

    const read = db.transaction('items', 'readonly');
    const [stored] = await Promise.all([
      result(read.objectStore('items').get('answer')),
      completed(read)
    ]);
    console.log(`Scope: ${scope}; stored after rollback: ${stored}; abort error: ${abortError?.name ?? 'null'}`);
  } catch (error) {
    if (!db && error.name === 'SecurityError') {
      console.log(`Transaction not started: ${error.name}`);
    } else {
      console.log(`Transaction example failed: ${error.name}`);
    }
  } finally {
    if (db) {
      db.close();
      await result(indexedDB.deleteDatabase(name));
    }
  }
})();

Result

Transaction not started: SecurityError

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources