Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 122 ยท Web APIs

IndexedDB

Store large amounts of structured data in the browser with IndexedDB. Learn databases, versions, object stores, transactions, indexes, cursors and key ranges.

Web Storage is perfect for a handful of small strings. But what if your app needs to keep hundreds of notes for offline use, a catalog of products, or images the user drew? Then you need IndexedDB: a real database built into every modern browser.

IndexedDB stores JavaScript objects (not just strings), can hold far more data than Web Storage, finds records quickly through indexes, and works asynchronously, so even big reads and writes never freeze the page. It is also available inside Web Workers. The price is a more verbose API with a few new ideas. This lesson walks through them in the order you use them: open a database, define its structure, then read and write inside transactions.

IndexedDB doesn't work in the editors on this page. They run in a sandbox with no origin of their own, so the browser refuses to open a database there. You will see that refusal in the first example. The full read-only listings below work in any normal page; save them as an .html file and open it from localhost to try them. The other live examples practice the parts that do work everywhere: which values can be stored and how key ranges select records.

The big picture

An IndexedDB setup has four layers:

Concept What it is Comparable to
Database A named container with a version number, private to your origin A database file
Object store A collection of records, each with a unique key A table
Index A second way to look records up, by one of their properties A table index
Transaction A group of reads and writes that succeed or fail together A transaction

A record is any value the browser can copy with the structured clone algorithm: objects, arrays, strings, numbers, dates, Maps, Sets, typed arrays, Blobs and Files. Functions and DOM elements can't be stored.

Opening a database

Everything starts with indexedDB.open(name, version). It returns a request object right away; the result arrives later through events:

JavaScript
const request = indexedDB.open('notes-app', 1);

request.addEventListener('upgradeneeded', () => {
  // Runs when the database is new or the version number went up.
  const db = request.result;
  const store = db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
  store.createIndex('by-tag', 'tag');
  store.createIndex('by-created', 'created');
});

request.addEventListener('success', () => {
  const db = request.result;      // ready to use
  console.log('Opened', db.name, 'version', db.version);
});

request.addEventListener('error', () => {
  console.error('Could not open the database:', request.error);
});

Three events matter:

  • upgradeneeded fires when the database doesn't exist yet or when you ask for a higher version than the one stored. It is the only place where you may create or delete object stores and indexes.
  • success gives you the open database in request.result.
  • error fires if opening fails, for example because storage is blocked.

Run this example to see what happens when a page is not allowed to use IndexedDB. Depending on the browser, the call either throws straight away or the request fires an error event, so the code handles both.

Trying to open a database

In a real app, show a friendly message in this situation and keep working without offline storage.

Versions and upgrades

The version number is how you change your database's structure later. Say version 1 shipped, and now you want a new archived index. Bump the version to 2 and handle each step in upgradeneeded, using event.oldVersion to see where each visitor is starting from:

JavaScript
const request = indexedDB.open('notes-app', 2);

request.addEventListener('upgradeneeded', (event) => {
  const db = request.result;

  if (event.oldVersion < 1) {
    const store = db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
    store.createIndex('by-tag', 'tag');
  }
  if (event.oldVersion < 2) {
    request.transaction.objectStore('notes').createIndex('by-archived', 'archived');
  }
});

A new visitor runs both steps; someone who already has version 1 runs only the second. If the page is open in another tab with the old version, that tab receives a versionchange event (close its database there with db.close()), and your request may fire blocked until it does.

Keys

Every record needs a unique key. You choose how keys are made when you create the store:

  • { keyPath: 'id' }: the key is read from the object's id property ("in-line" keys).
  • { keyPath: 'id', autoIncrement: true }: the browser generates 1, 2, 3โ€ฆ and writes it into id for you.
  • No keyPath: you pass the key separately, as in store.put(value, key).

Keys can be numbers, strings, dates, binary data or arrays of these.

Transactions

Every read and write happens inside a transaction. You open one on the database, naming the stores you need and a mode:

  • 'readonly' (the default) for reading. Many read-only transactions can run at the same time.
  • 'readwrite' for adding, changing or deleting.
JavaScript
function addNote(db, note) {
  const tx = db.transaction('notes', 'readwrite');
  const store = tx.objectStore('notes');

  store.add({ ...note, created: new Date() });

  tx.addEventListener('complete', () => console.log('Saved.'));
  tx.addEventListener('error', () => console.error('Not saved:', tx.error));
}

Transactions are all or nothing. If any request inside one fails, every change in it is rolled back. They also commit automatically as soon as no requests are pending, which leads to the most common IndexedDB bug: if you await something unrelated (a fetch(), a timer) in the middle of a transaction, it closes, and your next request throws a TransactionInactiveError. Fetch your data first, then open the transaction.

Reading and writing

Object stores offer these methods. Each returns a request with onsuccess and onerror:

Method Does
add(value) Inserts a record; fails if the key already exists
put(value) Inserts, or replaces the record with the same key
get(key) Reads one record (result is undefined if missing)
getAll(query?, count?) Reads many records as an array
getAllKeys() Reads only the keys
count(query?) Counts records
delete(key) Deletes one record, or every record in a key range
clear() Deletes every record in the store
JavaScript
const tx = db.transaction('notes');                 // readonly
const request = tx.objectStore('notes').get(3);

request.onsuccess = () => {
  const note = request.result;
  console.log(note ? note.title : 'No note with id 3');
};

Indexes

A store finds records by their key. An index lets you find them by another property instead. You created a by-tag index on the tag property earlier, so you can ask for all notes tagged "recipes":

JavaScript
const index = db.transaction('notes').objectStore('notes').index('by-tag');
const request = index.getAll('recipes');

request.onsuccess = () => {
  console.log(request.result);  // every note whose tag is "recipes"
};

createIndex() takes an options object as its third argument:

  • { unique: true } rejects two records with the same value, which is good for email addresses or usernames.
  • { multiEntry: true } for array properties: a note with tags: ['quick', 'vegan'] appears under both values.

Key ranges and cursors

To select a range of records instead of one, pass an IDBKeyRange to getAll(), count(), delete() or a cursor:

Range Matches keys
IDBKeyRange.only(x) equal to x
IDBKeyRange.lowerBound(x) โ‰ฅ x (pass true as a second argument for > x)
IDBKeyRange.upperBound(x) โ‰ค x (or < x with true)
IDBKeyRange.bound(a, b) between a and b; two optional flags exclude either end

Key ranges are ordinary objects that don't need a database, so you can experiment with them here. The includes() method tells you whether a key falls inside a range. Keys compare in a fixed order: numbers come before dates, dates before strings, and strings compare character by character.

Experimenting with key ranges

Look closely at the lowerBound(10) row: it matches every string too. Because every string sorts after every number, 'apple' counts as "at least 10". That surprise is a good reason to keep the keys in one store of a single type. Try adding your own ranges and keys to the code.

A cursor walks through records one at a time, in key order, which lets you process huge stores without loading everything at once:

JavaScript
const tx = db.transaction('notes');
const range = IDBKeyRange.lowerBound(new Date('2026-01-01'));
const request = tx.objectStore('notes').index('by-created').openCursor(range, 'prev');

request.onsuccess = () => {
  const cursor = request.result;
  if (!cursor) return;                 // no more records
  console.log(cursor.value.title);
  cursor.continue();                   // fires onsuccess again with the next one
};

The second argument to openCursor() sets the direction: 'next' (default) or 'prev' for newest first. In a readwrite transaction, cursor.update(value) and cursor.delete() change the current record.

What you can store

Records are copied with the structured clone algorithm, the same one used by postMessage(). You can test any value with the global structuredClone() function, which works even in this sandbox. If structuredClone() accepts a value, IndexedDB can store it.

Which values can be stored?

A Date comes back as a real Date and a Blob as a real Blob, which is a big advantage over JSON in Web Storage. Objects with methods and DOM elements throw a DataCloneError.

Promise wrappers

IndexedDB was designed before promises existed, so it uses request objects and events. Many developers wrap it in a few lines so they can use async/await:

JavaScript
function promisify(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

const tx = db.transaction('notes');
const note = await promisify(tx.objectStore('notes').get(3));

Small, well-tested libraries do the same thing more thoroughly. Whatever you use, the rule about not awaiting unrelated work inside a transaction still applies.

Storage limits and persistence

Browsers give each origin a share of the free disk space, usually far more than Web Storage's few megabytes. You can ask how much you are using:

JavaScript
const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${(usage / 1e6).toFixed(1)} MB of ${(quota / 1e6).toFixed(0)} MB`);

By default, stored data is best effort: if the device runs low on space, the browser may delete it. For data the user would hate to lose, request persistent storage with await navigator.storage.persist(), which resolves to true if the browser agrees. Even then, the user can always clear site data, so important data should also be synced to a server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where are you allowed to create object stores and indexes?

    Changing the database structure is only allowed during an upgrade, which runs when the database is new or the version number goes up.
  2. 2. You need to change an existing record, or create it if it doesn't exist. Which method fits?

    put() inserts or replaces. add() fails when a record with the same key already exists.
  3. 3. Inside a readwrite transaction you await fetch(...), then call store.put(). What is likely to happen?

    Transactions commit as soon as no requests are pending. Do unrelated async work before opening the transaction.
  4. 4. Your store's key is id, but you want to look up users by email quickly. What do you add?

    An index gives a second way to find records by a property. Use { unique: true } so no two users share an email.
  5. 5. Which value can NOT be stored in IndexedDB?

    Records are copied with structured clone, which supports dates, blobs and maps but not functions, so the object with a method throws a DataCloneError.

Summary

  • IndexedDB is an asynchronous, origin-private database for large amounts of structured data, available in pages and workers.
  • indexedDB.open(name, version) returns a request; create stores and indexes in upgradeneeded, and raise the version to change structure.
  • Object stores hold records with unique keys (keyPath, autoIncrement or explicit keys).
  • All reads and writes happen in transactions (readonly or readwrite) that are all-or-nothing and auto-commit, so don't await unrelated work inside them.
  • Indexes look records up by a property; IDBKeyRange and cursors handle ranges and large result sets.
  • Anything structuredClone() accepts can be stored. Check space with navigator.storage.estimate() and request persist() for precious data.

Next: Cross-Document Messaging with postMessage, where pages and iframes learn to talk to each other safely.