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 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.
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 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.
Dexie.js is a wrapper library for indexedDB - the standard database in the browser. https://dexie.org.
IndexedDB is the portable database for all browser engines. Dexie.js makes it fun and easy to work with.
But also:
<!DOCTYPE html>
<html>
<head>
<script type="module">
// Import Dexie
import { Dexie } from 'https://unpkg.com/dexie/dist/modern/dexie.mjs';
//
// Declare Database
//
const db = new Dexie('FriendDatabase');
db.version(1).stores({
friends: '++id, age'
});
//
// Play with it
//
try {
await db.friends.add({ name: 'Alice', age: 21 });
const youngFriends = await db.friends
.where('age')
.below(30)
.toArray();
alert(`My young friends: ${JSON.stringify(youngFriends)}`);
} catch (e) {
alert(`Oops: ${e}`);
}
</script>
</head>
</html>
Yes, it's that simple. Read the docs to get into the details.
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/dexie/dist/dexie.js"></script>
<script>
//
// Declare Database
//
const db = new Dexie('FriendDatabase');
db.version(1).stores({
friends: '++id, age'
});
//
// Play with it
//
db.friends.add({ name: 'Alice', age: 21 }).then(() => {
return db.friends
.where('age')
.below(30)
.toArray();
}).then(youngFriends => {
alert (`My young friends: ${JSON.stringify(youngFriends)}`);
}).catch (e => {
alert(`Oops: ${e}`);
});
</script>
</head>
</html>
Real-world apps are often built using components in various frameworks. Here's a version of Hello World written for React and Typescript. There are also links below this sample to more tutorials for different frameworks...
import React from 'react';
import { Dexie, type EntityTable } from 'dexie';
import { useLiveQuery } from 'dexie-react-hooks';
// Typing for your entities (hint is to move this to its own module)
export interface Friend {
id: number;
name: string;
age: number;
}
// Database declaration (move this to its own module also)
export const db = new Dexie('FriendDatabase') as Dexie & {
friends: EntityTable<Friend, 'id'>;
};
db.version(1).stores({
friends: '++id, age',
});
// Component:
export function MyDexieReactComponent() {
const youngFriends = useLiveQuery(() =>
db.friends
.where('age')
.below(30)
.toArray()
);
return (
<>
<h3>My young friends</h3>
<ul>
{youngFriends?.map((f) => (
<li key={f.id}>
Name: {f.name}, Age: {f.age}
</li>
))}
</ul>
<button
onClick={() => {
db.friends.add({ name: 'Alice', age: 21 });
}}
>
Add another friend
</button>
</>
);
}
Tutorials for React, Svelte, Vue, Angular and vanilla JS
Dexie has kick-ass performance. Its bulk methods take advantage of a lesser-known feature in IndexedDB that makes it possible to store stuff without listening to every onsuccess event. This speeds up the performance to a maximum.
above(key): Collection;
aboveOrEqual(key): Collection;
add(item, key?): Promise;
and(filter: (x) => boolean): Collection;
anyOf(keys[]): Collection;
anyOfIgnoreCase(keys: string[]): Collection;
below(key): Collection;
belowOrEqual(key): Collection;
between(lower, upper, includeLower?, includeUpper?): Collection;
bulkAdd(items: Array): Promise;
bulkDelete(keys: Array): Promise;
bulkPut(items: Array): Promise;
clear(): Promise;
count(): Promise;
delete(key): Promise;
distinct(): Collection;
each(callback: (obj) => any): Promise;
eachKey(callback: (key) => any): Promise;
eachPrimaryKey(callback: (key) => any): Promise;
eachUniqueKey(callback: (key) => any): Promise;
equals(key): Collection;
equalsIgnoreCase(key): Collection;
filter(fn: (obj) => boolean): Collection;
first(): Promise;
get(key): Promise;
inAnyRange(ranges): Collection;
keys(): Promise;
last(): Promise;
limit(n: number): Collection;
modify(changeCallback: (obj: T, ctx:{value: T}) => void): Promise;
modify(changes: { [keyPath: string]: any } ): Promise;
noneOf(keys: Array): Collection;
notEqual(key): Collection;
offset(n: number): Collection;
or(indexOrPrimayKey: string): WhereClause;
orderBy(index: string): Collection;
primaryKeys(): Promise;
put(item: T, key?: Key): Promise;
reverse(): Collection;
sortBy(keyPath: string): Promise;
startsWith(key: string): Collection;
startsWithAnyOf(prefixes: string[]): Collection;
startsWithAnyOfIgnoreCase(prefixes: string[]): Collection;
startsWithIgnoreCase(key: string): Collection;
toArray(): Promise;
toCollection(): Collection;
uniqueKeys(): Promise;
until(filter: (value) => boolean, includeStopEntry?: boolean): Collection;
update(key: Key, changes: { [keyPath: string]: any }): Promise;
This is a mix of methods from WhereClause, Table and Collection. Dive into the API reference to see the details.
Dexie Cloud is a commercial offering that can be used as an add-on to Dexie.js. It syncs a Dexie database with a server and enables developers to build apps without having to care about backend or database layer else than the frontend code with Dexie.js as the sole database layer.
Source for a sample Dexie Cloud app: Dexie Cloud To-do app
See the sample Dexie Cloud app in action: https://dexie.github.io/Dexie.js/dexie-cloud-todo-app/
https://dexie.org/docs/Samples
https://github.com/dexie/Dexie.js/tree/master/samples
https://dexie.org/docs/Questions-and-Answers
npm install dexie
For those who don't like package managers, here's the download links:
https://unpkg.com/dexie@latest/dist/dexie.min.js
https://unpkg.com/dexie@latest/dist/dexie.min.js.map
https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs
https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs.map
https://unpkg.com/dexie@latest/dist/dexie.d.ts
See CONTRIBUTING.md
pnpm install
pnpm run build
pnpm test
pnpm run watch