Course contentsShow
← Web Development
Lesson 788 of 2,98214. Browser StorageFree lesson

Transactions: Read, Write, and Lifecycle

Master transaction modes, auto-commit behavior, and proper transaction scope management.

Transactions: Read, Write, and Lifecycle

You'll learn how IndexedDB transactions work, including modes, auto-commit behavior, and when they complete.

What is a Transaction?

In IndexedDB, every operation (reading, writing, or deleting data) must happen inside a transaction. Think of a transaction like a work session at a library: you check out books (start transaction), make changes (read/write), then return everything and close your session (transaction completes). If something goes wrong, the library can undo your changes.

Transaction Modes

IndexedDB supports two main transaction modes:

  • readonly - Only for reading data. Multiple readonly transactions can run simultaneously. This is the default mode.
  • readwrite - For reading and writing data. Only one readwrite transaction per object store at a time to prevent conflicts.

When you open a database connection, you create transactions like this:

const transaction = db.transaction('storeName', 'readonly');
// or
const writeTransaction = db.transaction('storeName', 'readwrite');

Auto-Commit and Lifecycle

Transactions auto-commit when all requests complete and the browser returns to the event loop. You don't manually commit. The transaction lifecycle:

  1. Active - You can make requests
  2. Inactive - Briefly inactive between event loop cycles
  3. Complete - All operations succeeded (fires oncomplete)
  4. Aborted - Something failed (fires onerror or onabort)

Critical rule: Once the transaction becomes inactive, you cannot add new requests. Keep all operations synchronous within the same function.

Key Takeaway: IndexedDB transactions require explicit mode selection, auto-commit when requests finish, and become inactive once control returns to the event loop—plan all operations upfront within the same execution context.