Getting started with HTML5 IndexedDB
A real database in the browser: store structured data, query it, and keep it offline.
This guide revisits and updates an original tutorial from noiretaya.com (
log.noiretaya.com/231). The code has been refreshed for current versions.Open a database
IndexedDB is asynchronous and versioned. Create your object stores inside onupgradeneeded.
const request = indexedDB.open('notes-db', 1);
request.onupgradeneeded = (e) => {
const db = e.target.result;
const store = db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
store.createIndex('byTag', 'tag', { unique: false });
};
Add and read records
All reads and writes happen inside a transaction.
request.onsuccess = (e) => {
const db = e.target.result;
// write
const tx = db.transaction('notes', 'readwrite');
tx.objectStore('notes').add({ text: 'Hello', tag: 'memo' });
// read all
const ro = db.transaction('notes').objectStore('notes');
ro.getAll().onsuccess = (ev) => console.log(ev.target.result);
};
When to use it: IndexedDB suits larger or structured offline data (drafts, caches, queues) where
localStorage's string-only, synchronous API falls short.