← Back to archive

Repo of the Day

jakearchibald/idb

Published: Dec 6, 2023

Open repository ↗

Summary

idb is a small (~1.19kB brotli'd, per the README) TypeScript library that wraps the browser IndexedDB API, replacing event-driven IDBRequest objects with promises while keeping the same shape. It is published under the ISC license and targets modern browsers (Chrome, Firefox, Safari, Edge); IE is not supported.

What it is useful for

idb is useful when a web application needs structured client-side storage and the native IndexedDB API feels too verbose. Concrete scenarios from the README include:

  • Replacing IDBRequest.onsuccess = ... callbacks with await, e.g. await store.get(key).
  • Caching structured records, as in the README's "article store" example with keyPath: 'id' and an index on a date field.
  • Adding type safety through TypeScript's DBSchema interface, where wrong value types become compile-time errors. The README shows db.put('favourite-number', 'Twelve', 'Jake') failing because the store expects a number.
  • A simple async key/value layer similar to localStorage, shown in the README's "Keyval store" example.

How engineers can use it

Install via npm:

npm install idb

Then import and open a database:

import { openDB, deleteDB, wrap, unwrap } from 'idb';

const db = await openDB('my-db', 1, {
  upgrade(db) {
    db.createObjectStore('keyval');
  },
});

await db.put('keyval', 42, 'counter');
const value = await db.get('keyval', 'counter');

The upgrade callback runs when the version increases and is where you create stores and indexes, mirroring the native upgradeneeded event.

Documented enhancements include:

  • Shortcuts like db.get, db.put, db.getAll, and db.getFromIndex that replace creating a transaction for a single operation.
  • tx.store, which references the object store directly when a transaction involves only one store.
  • tx.done, a promise that resolves when the transaction commits or rejects with the transaction error.
  • Cursor support for for await (const cursor of tx.store) async iteration and an .iterate(range) method on stores and indexes.

Documented limitations:

  • Transactions auto-close when the microtask queue empties. The README explicitly warns not to await unrelated work, such as fetch, between the first and last operation in a transaction, or it will abort.
  • IE is not supported.

For a lighter key/value-only wrapper, the README points to idb-keyval, noting you can upgrade to idb later. To work on the library itself, the README documents pnpm run dev and browser-based testing via build/test/, which requires a basic local web server such as serve.