gitmyhub

idb

TypeScript ★ 7.4k updated 1y ago

IndexedDB, but with promises

A tiny 1.19KB JavaScript library that wraps the browser's built-in IndexedDB storage in a modern promise-based API, making offline data storage as straightforward to write as any other async JavaScript.

TypeScriptJavaScriptnpmwebpackRollupsetup: easycomplexity 2/5

The idb library is a small JavaScript wrapper around IndexedDB, a database built directly into web browsers. IndexedDB lets websites store data on a user's device so it can be accessed later, even without an internet connection. The native IndexedDB API uses an older style of handling results through event callbacks, which tends to produce tangled, hard-to-read code. This library replaces that style with promises, which is how modern JavaScript code handles operations that take a moment to complete.

In practical terms, reading and writing to the local database looks much like any other modern JavaScript code. You can use the await keyword to wait for a result instead of wiring up callback functions. The library also adds shortcut methods for common one-off operations such as getting or putting a value, so you do not need to manually set up a transaction for each simple task.

The file weighs about 1.19 kilobytes after compression, making it inexpensive to include on a web page. It can be installed as an npm package and imported in projects built with bundlers like webpack or Rollup, or loaded directly in the browser from a CDN address with no build step required.

One important constraint described in the README: IndexedDB transactions close automatically once JavaScript finishes processing its current batch of work. If you make an unrelated network request in the middle of a transaction, the transaction may close before you are done, which causes an error. The library does not change this browser behavior, and the README includes an example showing exactly where the failure happens and why.

Where it fits