dexie, idb-keyval, and localforage are JavaScript libraries that simplify working with client-side storage in web browsers. All three build on top of IndexedDB — the browser’s built-in, asynchronous key-value database — but offer different levels of abstraction, feature sets, and developer ergonomics. They enable persistent data storage beyond simple localStorage, supporting complex queries, large datasets, and offline-first applications without blocking the main thread.
When your web app needs to store data locally — whether for offline support, performance caching, or user preferences — you quickly outgrow localStorage. It’s synchronous, size-limited, and blocks the main thread. The modern solution is IndexedDB, but its raw API is verbose and callback-heavy. That’s where libraries like dexie, idb-keyval, and localforage come in. They all wrap IndexedDB, but with very different philosophies. Let’s compare how they handle real-world tasks.
dexie treats IndexedDB like a real database — with tables, schemas, and indexes.
// dexie: Define a table with schema
import Dexie from 'dexie';
const db = new Dexie('MyApp');
db.version(1).stores({
contacts: '++id, name, email', // auto-incrementing id, indexes on name/email
});
// Insert and query
await db.contacts.add({ name: 'Alice', email: 'alice@example.com' });
const matches = await db.contacts.where('name').startsWith('A').toArray();
idb-keyval offers zero structure — just a global key-value store.
get, set, del, clear.// idb-keyval: Simple key-value operations
import { get, set, del } from 'idb-keyval';
await set('user-token', 'abc123');
const token = await get('user-token');
await del('user-token');
localforage also uses a flat key-value model, but mimics the localStorage API.
// localforage: localStorage-like async API
import localforage from 'localforage';
await localforage.setItem('theme', 'dark');
const theme = await localforage.getItem('theme');
await localforage.removeItem('theme');
Only dexie supports rich querying.
between, above, startsWith).and/or.// dexie: Complex query
const recentActiveUsers = await db.users
.where('lastActive')
.above(Date.now() - 7 * 24 * 60 * 60 * 1000)
.filter(user => user.status === 'active')
.sortBy('name');
idb-keyval and localforage have no query API.
// idb-keyval/localforage: No native query support
// You'd have to do this (not recommended for large data):
const allKeys = await localforage.keys();
const matching = [];
for (const key of allKeys) {
const value = await localforage.getItem(key);
if (value && value.category === 'urgent') matching.push(value);
}
dexie includes built-in versioned schema migrations.
// dexie: Schema migration
db.version(2).stores({
contacts: '++id, name, email, phone', // added 'phone'
}).upgrade(tx => {
return tx.table('contacts').toCollection().modify(contact => {
contact.phone = null; // initialize new field
});
});
idb-keyval and localforage have no concept of schema.
All three use asynchronous IndexedDB operations, so none block the main thread.
dexie supports explicit transactions for batch operations:
// dexie: Batch write in a single transaction
await db.transaction('rw', db.contacts, async () => {
await db.contacts.add({ name: 'Bob' });
await db.contacts.add({ name: 'Carol' });
});
// Both writes happen in one IndexedDB transaction
idb-keyval batches operations automatically under the hood when possible, but you can’t control transaction boundaries.
localforage does not group operations — each setItem is a separate IndexedDB transaction, which can be slower for bulk writes.
Only dexie provides live data observation:
// dexie: Watch for changes
db.contacts.hook('updating', (modifications, primaryKey, obj) => {
console.log('Contact updated:', obj);
});
// Or observe queries reactively (with dexie-observable plugin)
idb-keyval and localforage offer no built-in change listeners. You’d need to layer your own event system or use external state management.
localforage stands out by automatically falling back to WebSQL or localStorage if IndexedDB is unavailable (e.g., in older browsers or private browsing modes with quota limits).
dexie and idb-keyval require IndexedDB and will fail if it’s not supported or disabled. This is usually fine in modern apps targeting current browsers, but worth noting for broad compatibility.
dexie if:idb-keyval if:localforage if:localStorage in an existing codebase and want minimal changes.| Feature | dexie | idb-keyval | localforage |
|---|---|---|---|
| Data Model | Tables with schemas | Flat key-value | Flat key-value |
| Query API | ✅ Rich, indexed queries | ❌ None | ❌ None |
| Schema Migrations | ✅ Built-in | ❌ N/A | ❌ N/A |
| Transactions | ✅ Explicit control | ⚠️ Automatic batching | ❌ Per-operation |
| Observability | ✅ Hooks & live queries | ❌ None | ❌ None |
| Storage Fallbacks | ❌ IndexedDB only | ❌ IndexedDB only | ✅ WebSQL / localStorage |
| Best For | Structured, query-heavy apps | Simple key-value caching | localStorage replacement |
These libraries solve different problems under the same umbrella. Don’t pick based on popularity — pick based on your data shape. If you’re storing more than a handful of independent values and ever need to “find” data rather than “look up” by key, dexie is worth the slight learning curve. For everything else, idb-keyval gives you the leanest path to async storage, while localforage eases legacy transitions.
Choose localforage when you want a drop-in replacement for localStorage that automatically uses IndexedDB (or fallbacks like WebSQL) under the hood while maintaining a familiar async API. It’s well-suited for teams migrating from synchronous storage or building apps that need reliable async persistence without complex data relationships.
Choose idb-keyval when your use case is limited to simple key-value storage — like caching tokens, preferences, or small blobs — and you want the smallest possible abstraction over IndexedDB with zero configuration. It’s perfect for lightweight needs where you don’t require queries, indexes, or schema management.
Choose dexie when you need a full-featured IndexedDB wrapper with support for advanced querying, transactions, versioned schema migrations, and reactive data observation. It’s ideal for applications that manage structured data (like task lists, message histories, or cached API responses) and require robust data modeling without sacrificing performance.
localForage is a fast and simple storage library for JavaScript. localForage
improves the offline experience of your web app by using asynchronous storage
(IndexedDB or WebSQL) with a simple, localStorage-like API.
localForage uses localStorage in browsers with no IndexedDB or WebSQL support. See the wiki for detailed compatibility info.
To use localForage, just drop a single JavaScript file into your page:
<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>
Try the live example.
Download the latest localForage from GitHub, or install with npm:
npm install localforage
Lost? Need help? Try the localForage API documentation. localForage API文档也有中文版。
If you're having trouble using the library, running the tests, or want to contribute to localForage, please look through the existing issues for your problem first before creating a new one. If you still need help, feel free to file an issue.
Because localForage uses async storage, it has an async API. It's otherwise exactly the same as the localStorage API.
localForage has a dual API that allows you to either use Node-style callbacks or Promises. If you are unsure which one is right for you, it's recommended to use Promises.
Here's an example of the Node-style callback form:
localforage.setItem('key', 'value', function (err) {
// if err is non-null, we got an error
localforage.getItem('key', function (err, value) {
// if err is non-null, we got an error. otherwise, value is the value
});
});
And the Promise form:
localforage.setItem('key', 'value').then(function () {
return localforage.getItem('key');
}).then(function (value) {
// we got our value
}).catch(function (err) {
// we got an error
});
Or, use async/await:
try {
const value = await localforage.getItem('somekey');
// This code runs once the value has been loaded
// from the offline store.
console.log(value);
} catch (err) {
// This code runs if there were any errors.
console.log(err);
}
For more examples, please visit the API docs.
You can store any type in localForage; you aren't limited to strings like in
localStorage. Even if localStorage is your storage backend, localForage
automatically does JSON.parse() and JSON.stringify() when getting/setting
values.
localForage supports storing all native JS objects that can be serialized to JSON, as well as ArrayBuffers, Blobs, and TypedArrays. Check the API docs for a full list of types supported by localForage.
All types are supported in every storage backend, though storage limits in localStorage make storing many large Blobs impossible.
You can set database information with the config() method.
Available options are driver, name, storeName, version, size, and
description.
Example:
localforage.config({
driver : localforage.WEBSQL, // Force WebSQL; same as using setDriver()
name : 'myApp',
version : 1.0,
size : 4980736, // Size of database, in bytes. WebSQL-only for now.
storeName : 'keyvaluepairs', // Should be alphanumeric, with underscores.
description : 'some description'
});
Note: you must call config() before you interact with your data. This
means calling config() before using getItem(), setItem(), removeItem(),
clear(), key(), keys() or length().
You can create multiple instances of localForage that point to different stores
using createInstance. All the configuration options used by
config are supported.
var store = localforage.createInstance({
name: "nameHere"
});
var otherStore = localforage.createInstance({
name: "otherName"
});
// Setting the key on one of these doesn't affect the other.
store.setItem("key", "value");
otherStore.setItem("key", "value2");
You can use localForage with RequireJS:
define(['localforage'], function(localforage) {
// As a callback:
localforage.setItem('mykey', 'myvalue', console.log);
// With a Promise:
localforage.setItem('mykey', 'myvalue').then(console.log);
});
If you have the allowSyntheticDefaultImports compiler option set to true in your tsconfig.json (supported in TypeScript v1.8+), you should use:
import localForage from "localforage";
Otherwise you should use one of the following:
import * as localForage from "localforage";
// or, in case that the typescript version that you are using
// doesn't support ES6 style imports for UMD modules like localForage
import localForage = require("localforage");
If you use a framework listed, there's a localForage storage driver for the models in your framework so you can store data offline with localForage. We have drivers for the following frameworks:
If you have a driver you'd like listed, please open an issue to have it added to this list.
You can create your own driver if you want; see the
defineDriver API docs.
There is a list of custom drivers on the wiki.
You'll need node/npm and bower.
To work on localForage, you should start by
forking it and installing its
dependencies. Replace USERNAME with your GitHub username and run the
following:
# Install bower globally if you don't have it:
npm install -g bower
# Replace USERNAME with your GitHub username:
git clone git@github.com:USERNAME/localForage.git
cd localForage
npm install
bower install
Omitting the bower dependencies will cause the tests to fail!
You need PhantomJS installed to run local tests. Run npm test (or,
directly: grunt test). Your code must also pass the
linter.
localForage is designed to run in the browser, so the tests explicitly require a browser environment. Local tests are run on a headless WebKit (using PhantomJS).
When you submit a pull request, tests will be run against all browsers that localForage supports on Travis CI using Sauce Labs.
As of version 1.7.3 the payload added to your app is rather small. Served using gzip compression, localForage will add less than 10k to your total bundle size:
This program is free software; it is distributed under an Apache License.
Copyright (c) 2013-2016 Mozilla (Contributors).