CKTIS / JavaScript
IndexedDB: creating object stores and opening transactions
Use `createObjectStore()` to change the schema during a database upgrade, and `transaction()` to read or write records in existing object stores.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
db.createObjectStore(name) → IDBObjectStore
db.createObjectStore(name, options) → IDBObjectStore
db.transaction(storeNames) → IDBTransaction
db.transaction(storeNames, mode) → IDBTransaction
db.transaction(storeNames, mode, options) → IDBTransactionIDBDatabase.createObjectStore/transaction refers to two methods on the same open IndexedDB connection. db.createObjectStore(name, options) immediately returns a new IDBObjectStore, but works only in an active versionchange transaction. IndexedDB starts that transaction when indexedDB.open() creates the database or opens it at a higher version; change the schema in upgradeneeded. An open connection in another tab can block the upgrade: the open request fires blocked, and the old connection can call close() in response to versionchange.
The optional keyPath tells IndexedDB where to extract the key from the value, such as id; an array of paths defines a compound key, while omitting the path means the key is stored separately. autoIncrement defaults to false; true enables a key generator but cannot be combined with an empty string or an array as keyPath (InvalidAccessError). A duplicate store name throws ConstraintError, an invalid key path throws SyntaxError, and calling without an upgrade transaction throws InvalidStateError.
db.transaction(storeNames, mode, options) immediately returns an IDBTransaction scoped to a single store name passed as a string or to a nonempty iterable of existing store names, such as an array or a Set. Get a store in that scope with tx.objectStore(name). The default "readonly" mode permits reads only; "readwrite" also permits writes. You cannot select "versionchange" here (TypeError). An unknown store gives NotFoundError, an empty list gives InvalidAccessError, and a closing or closed connection gives InvalidStateError. Optional options.durability ("default", "strict", "relaxed") is a commit durability hint; check target browser support.
Queue requests only while the transaction is active: in the task that created it or in one of its requests’ success or error handlers. Do not assume it stays active across await fetch(...): it may auto-commit, and a later request can throw TransactionInactiveError. A request succeeding does not mean the transaction succeeded. complete confirms commit; abort means changes were rolled back.
IndexedDB is a Web API, not part of ECMAScript 2024. Access is limited to the same origin; browser settings can restrict storage access or how long data is kept.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IndexedDB example</title>
</head>
<body>
<script>
(async () => {
const idb = window.indexedDB;
const name = `cktis-notes-${crypto.randomUUID()}`;
const requestResult = (request) => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const finished = (tx) => new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error ?? new Error("Transaction aborted"));
});
const open = idb.open(name, 1);
open.onupgradeneeded = () => {
open.result.createObjectStore("notes", { keyPath: "id" });
};
const db = await requestResult(open);
db.onversionchange = () => db.close();
let title;
try {
const write = db.transaction("notes", "readwrite");
write.objectStore("notes").put({ id: 1, title: "IndexedDB" });
await finished(write);
const read = db.transaction("notes");
const get = read.objectStore("notes").get(1);
await finished(read);
title = get.result.title;
} finally {
db.close();
await requestResult(idb.deleteDatabase(name));
}
console.log(title);
})().catch((error) => console.error(error));
</script>
</body>
</html>Result
IndexedDB
Serve the HTML file over HTTPS and open it in a browser where storage is allowed. The example creates a randomly named database, reads the record after the write commits, closes and deletes the database, then prints `IndexedDB` in the browser console.
Related lessons
- JavaScript · Lesson 31 · Advanced · Version: 4
Sources
- IDBDatabase: createObjectStore() method
- IDBDatabase: transaction() method
- IDBFactory: open() method
- Using IndexedDB
- IDBTransaction
- IDBTransaction: durability property
- IndexedDB key characteristics and basic terminology
- IDBObjectStore: put() method
- IDBObjectStore: get() method
- IDBFactory: deleteDatabase() method
- Crypto: randomUUID() method
- ECMAScript® 2024 Language Specification — Overview