JavaScript Reference ยท Browser and Web APIs
IndexedDB
Reference for IndexedDB: open a database, create object stores and indexes, run transactions, read and write records, use cursors and avoid common mistakes.
IndexedDB is a database built into the browser. It stores JavaScript values (anything the structured clone algorithm can copy, including objects, arrays, dates, blobs and files) in object stores, looks them up by key or through indexes, and does all of it asynchronously so large datasets do not freeze the page. It is the right tool when localStorage is too small, too slow or too flat: offline data, caches of API results, drafts with attachments.
The native API is event-based and verbose: you make a request, then wait for its success or error event. Many projects wrap it in promises or use a small library, but the concepts below are the same either way.
const request = indexedDB.open("notes-app", 1); request.onsuccess = () => console.log("opened", request.result.name);
Try it
IndexedDB is not available in the preview sandbox, because the preview has no origin of its own. This example checks for it and reports the outcome instead of crashing.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The openDatabase() helper turns the event style into a promise. This second example shows the same trick with a stand-in request object, which you can run anywhere.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The workflow
A typical session has five steps. Here is a complete, read-only example (it needs a real page):
// 1. Open (or create) the database. Changing the version triggers an upgrade. const open = indexedDB.open("notes-app", 1); // 2. Define the schema, only inside onupgradeneeded. open.onupgradeneeded = () => { const db = open.result; const store = db.createObjectStore("notes", { keyPath: "id", autoIncrement: true }); store.createIndex("by_tag", "tag", { unique: false }); }; open.onsuccess = () => { const db = open.result; // 3. Every read or write happens in a transaction. const tx = db.transaction("notes", "readwrite"); const notes = tx.objectStore("notes"); // 4. Make requests on the store. notes.add({ title: "First", tag: "work" }); notes.put({ id: 1, title: "First (edited)", tag: "work" }); notes.get(1).onsuccess = (event) => console.log(event.target.result); notes.index("by_tag").getAll("work").onsuccess = (event) => { console.log(event.target.result.length, "work notes"); }; // 5. The transaction commits on its own when no requests remain. tx.oncomplete = () => db.close(); tx.onerror = () => console.error(tx.error); };
Main objects and methods
| Object | Members |
|---|---|
indexedDB |
open(name, version), deleteDatabase(name), databases(), cmp(a, b) |
IDBDatabase |
createObjectStore(), deleteObjectStore(), transaction(stores, mode), objectStoreNames, close() |
IDBObjectStore |
add(), put(), get(), getAll(), getAllKeys(), delete(), clear(), count(), openCursor(), createIndex(), index() |
IDBIndex |
get(), getAll(), count(), openCursor() on the indexed property |
IDBTransaction |
objectStore(), commit(), abort(), events complete, error, abort |
IDBKeyRange |
only(), lowerBound(), upperBound(), bound() for range queries |
add() fails if the key exists; put() inserts or replaces. Transaction modes are "readonly" (default), "readwrite" and, for schema changes, the special versionchange transaction inside onupgradeneeded.
Usage notes
- Schema changes only happen in
onupgradeneeded, which runs when the requested version is higher than the stored one. Increase the number each time the schema changes, and write the upgrade steps to run from any older version. - Transactions finish by themselves. If you wait on something other than an IndexedDB request (a
fetch(), a timer) the transaction closes and later calls throwTransactionInactiveError. Fetch first, then open the transaction. - Close old connections. When another tab wants a newer version, your connection gets a
versionchangeevent; calldb.close()there, or the upgrade stays blocked. - Keys. Use
keyPathfor an existing property,autoIncrementfor generated numbers. Keys can be numbers, strings, dates, binary data or arrays of those. - Same-origin, quota-limited. Storage is shared per origin and can be evicted under pressure;
navigator.storage.persist()asks the browser to keep it. - Errors bubble. Request errors bubble to the transaction; handle them there, and call
event.preventDefault()if you want to keep the transaction alive. - No SQL, no joins. Model your data around the queries you need and add indexes for them.
- Data is not secret. Anything stored is readable by scripts on the page.
Browser support
IndexedDB works in every current browser, though availability can be limited in private modes, sandboxed frames and some embedded views. Newer additions, such as transaction durability options, vary between browsers, so check a compatibility table.