CKTIS / JavaScript
Opening IndexedDB: upgradeneeded, blocked, success, and error
Tell when an IndexedDB open request needs a schema upgrade, is waiting for a connection to close, has succeeded, or has failed.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const request = indexedDB.open(name); // or indexedDB.open(name, version)
request.addEventListener("upgradeneeded", onUpgradeNeeded);
request.addEventListener("blocked", onBlocked);
request.addEventListener("success", onSuccess);
request.addEventListener("error", onError);
// Alternatively, assign one handler to each property:
request.onupgradeneeded = onUpgradeNeeded;
request.onblocked = onBlocked;
request.onsuccess = onSuccess;
request.onerror = onError;IDBOpenDBRequest.upgradeneeded/blocked/success/error groups the four events to handle when opening an IndexedDB database. indexedDB.open(name, version) immediately returns an IDBOpenDBRequest, not a Promise; opening is asynchronous. The request inherits success and error from IDBRequest. Omit version to open the existing version or create a database at version 1. IndexedDB is a web platform API, not part of ECMAScript; access depends on the runtime and storage settings.
upgradeneeded fires for a new database (oldVersion === 0) or when requesting a higher version. Use the event's oldVersion and newVersion to decide which migrations to run. Make schema changes through request.result within the active versionchange transaction at request.transaction. Do not assume it stays active while awaiting unrelated work such as fetch().
blocked means the upgrade request is waiting for another connection to the same database to close. IndexedDB skips sending versionchange to a connection that is already marked for closure, but that connection can still delay the upgrade until its transactions finish. In an app, handle versionchange on the existing IDBDatabase connection and call close() there. Use blocked to tell the user why the open request is waiting. There is no need to issue the request again.
success means request.result is the open IDBDatabase connection. If an upgrade was needed, its transaction has already committed. Opening at the current version does not fire upgradeneeded. A successful open does not guarantee that later transactions will succeed.
error means the request failed. Read the DOMException from request.error. Requesting a version below the stored version produces VersionError; aborting the upgrade transaction rolls back its changes and fails the open. A synchronous error, such as TypeError for version 0, is thrown by open() itself instead of firing an error event.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IndexedDB open request events</title>
</head>
<body>
<pre id="output"></pre>
<script>
(async () => {
const { indexedDB, crypto } = window;
const output = document.getElementById("output");
const name = `ck-tis-idb-${crypto.randomUUID()}`;
function log(line) {
output.textContent += (output.textContent ? "\n" : "") + line;
console.log(line);
}
function open(version, releaseBlocker) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onupgradeneeded = ({ oldVersion, newVersion }) => {
log(`upgradeneeded: ${oldVersion} -> ${newVersion}`);
const db = request.result;
if (oldVersion < 1) db.createObjectStore("notes");
if (oldVersion < 2 && newVersion >= 2) db.createObjectStore("tags");
};
request.onblocked = () => {
log(`blocked: ${version}`);
releaseBlocker?.();
};
request.onsuccess = () => {
log(`success: ${request.result.version}`);
resolve(request.result);
};
request.onerror = () => reject(request.error);
});
}
let first;
let second;
try {
first = await open(1);
// Intentionally keep version 1 open until the next request is blocked.
second = await open(2, () => first.close());
try {
const unexpected = await open(1);
unexpected.close();
throw new Error("Expected VersionError");
} catch (error) {
if (error.name !== "VersionError") throw error;
log(`error: ${error.name}`);
}
} finally {
first?.close();
second?.close();
const cleanup = indexedDB.deleteDatabase(name);
cleanup.onerror = () => console.error(cleanup.error);
}
})().catch((error) => console.error(error));
</script>
</body>
</html>Result
upgradeneeded: 0 -> 1 success: 1 blocked: 2 upgradeneeded: 1 -> 2 success: 2 error: VersionError
Open the HTML page over HTTPS or from localhost in a browser with IndexedDB and `crypto.randomUUID()` available. The demo deliberately keeps the version `1` connection open until `blocked`. Closing it lets the same request open version `2`. The next request for version `1` fails with `VersionError`.
Related lessons
- JavaScript · Lesson 20 · Intermediate · Version: 3
- JavaScript · Lesson 21 · Intermediate · Version: 3
Sources
- IDBOpenDBRequest
- IDBFactory: open() method
- IDBOpenDBRequest: upgradeneeded event
- IDBOpenDBRequest: blocked event
- IDBRequest: success event
- IDBRequest: error event
- IDBRequest: error property
- IDBRequest: transaction property
- IDBVersionChangeEvent
- IDBDatabase: versionchange event
- Using IndexedDB
- Crypto: randomUUID() method