CKTIS / JavaScript
IndexedDB: add, read, delete, and replace records
Use `add()`, `getAll()`, `delete()`, and `put()` to work with records by primary key, and distinguish a successful request from a committed transaction.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
store.add(value)
store.add(value, key)
store.getAll()
store.getAll(query)
store.getAll(query, count)
store.getAll(options)
store.delete(keyOrRange)
store.put(value)
store.put(value, key)IDBObjectStore.add/getAll/delete/put groups four IndexedDB methods, not ECMAScript features. You obtain an object store from a transaction. Access to the data follows the same-origin policy (scheme, host, and port), and support depends on the runtime.
add(value) inserts only: if the primary key already exists, the request fails with ConstraintError. put(value) inserts or replaces the entire value at that key; it does not merge fields. With an inline key, omit the second argument: keyPath identifies the key in the value. With an out-of-line key, pass key as the second argument unless an enabled key generator is to supply it. Both methods store a structured clone of the value and set request.result to the key on success. A value that cannot be cloned, such as a function, causes a synchronous DataCloneError.
getAll() puts an array of cloned values in request.result, with no separately attached keys; no matches yield []. The default order is ascending primary key order, not insertion order. getAll(query, count) lets you select a key or an IDBKeyRange and cap the results with a positive count. The getAll({ query, count, direction }) form also lets you set the direction, for example "prev" for descending order; check support for this form in your target browsers.
delete(keyOrRange) removes a record by primary key or all records in an IDBKeyRange. The successful request result is undefined, even if nothing matched. This method is not the JavaScript delete operator; use clear() to empty the store.
All four methods return an IDBRequest immediately, not a Promise. A readonly transaction is enough for reads; ordinary writes need readwrite. Queue requests while the transaction is active, such as when you create it or in a request event handler, not after waiting for a network response. By default, a request error aborts the transaction and rolls back its changes. success describes one request; the transaction's complete event confirms the commit.
Examples
void (async () => {
const { indexedDB, crypto } = globalThis;
if (!indexedDB || typeof crypto?.randomUUID !== 'function') {
throw new Error('Run this example on an HTTPS page in a browser with IndexedDB and crypto.randomUUID() available.');
}
const name = `cktis-idb-${crypto.randomUUID()}`;
const open = indexedDB.open(name, 1);
open.onupgradeneeded = () => {
open.result.createObjectStore('tasks', { keyPath: 'id' });
};
const db = await new Promise((resolve, reject) => {
open.onsuccess = () => resolve(open.result);
open.onerror = () => reject(open.error);
});
try {
const tx = db.transaction('tasks', 'readwrite');
const store = tx.objectStore('tasks');
store.add({ id: 2, title: 'Draft', tag: 'temporary' });
store.add({ id: 1, title: 'Remove me' });
const before = store.getAll();
store.put({ id: 2, title: 'Published' });
store.delete(1);
const after = store.getAll();
await new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error ?? new Error('Transaction aborted'));
});
console.log(JSON.stringify(before.result));
console.log(JSON.stringify(after.result));
} finally {
db.close();
const cleanup = indexedDB.deleteDatabase(name);
await new Promise((resolve, reject) => {
cleanup.onsuccess = () => resolve();
cleanup.onerror = () => reject(cleanup.error);
});
}
})().catch((error) => console.error(error));Result
[{"id":1,"title":"Remove me"},{"id":2,"title":"Draft","tag":"temporary"}]
[{"id":2,"title":"Published"}]Run this in the developer console of an HTTPS page where IndexedDB and `crypto.randomUUID()` are available and storage is permitted. After the commit, the first line shows both records in key order. The second shows that `put()` did not preserve `tag` and `delete()` removed the record with key `1`. The code closes the connection and requests deletion of the temporary database.
Related lessons
- JavaScript · Lesson 20 · Intermediate · Version: 3
Sources
- IDBObjectStore: add() method
- IDBObjectStore: getAll() method
- IDBObjectStore: delete() method
- IDBObjectStore: put() method
- IDBTransaction
- IDBTransaction: complete event
- IndexedDB key characteristics and basic terminology
- IDBDatabase: createObjectStore() method
- HTML Standard — Safe passing of structured data
- IDBFactory: open() method
- IDBFactory: deleteDatabase() method
- Crypto: randomUUID() method