dexie vs idb-keyval vs localforage
Client-Side Storage Libraries for Web Applications
dexieidb-keyvallocalforageSimilar Packages:

Client-Side Storage Libraries for Web Applications

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
dexie922,61814,1243.09 MB5893 months agoApache-2.0
idb-keyval03,160928 kB2510 months agoApache-2.0
localforage025,767-2495 years agoApache-2.0

Client-Side Storage Showdown: Dexie vs idb-keyval vs localForage

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.

🗃️ Data Model: Structured Tables vs Flat Key-Value

dexie treats IndexedDB like a real database — with tables, schemas, and indexes.

  • Define tables upfront with versioned schemas.
  • Support for compound indexes, primary keys, and relations.
  • Query using a fluent, promise-based API.
// 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.

  • No tables, no schemas, no indexes.
  • Keys are strings; values can be any serializable object.
  • Only four methods: 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.

  • Keys are strings; values are arbitrary objects.
  • Supports async/await or callbacks.
  • Automatically falls back to WebSQL or localStorage if IndexedDB isn’t available.
// localforage: localStorage-like async API
import localforage from 'localforage';

await localforage.setItem('theme', 'dark');
const theme = await localforage.getItem('theme');
await localforage.removeItem('theme');

🔍 Query Capabilities: From None to Full SQL-Like Expressions

Only dexie supports rich querying.

  • Filter by index ranges (between, above, startsWith).
  • Combine conditions with and/or.
  • Sort, limit, offset, and count results.
// 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.

  • To find data, you must retrieve everything and filter in JavaScript — inefficient for large datasets.
  • Best practice: only store small, isolated values you access by known key.
// 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);
}

🧱 Schema Management and Migrations

dexie includes built-in versioned schema migrations.

  • Declare database versions and how to upgrade between them.
  • Handle data transformation during upgrades.
// 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.

  • Since they store unstructured key-value pairs, there’s nothing to migrate.
  • If your app’s data format changes, you must handle backward compatibility manually (e.g., detect old formats at read time).

⚡ Performance and Concurrency

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.

🔄 Observability and Reactivity

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.

📦 Fallbacks and Browser Support

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.

💡 Real-World Guidance

Use dexie if:

  • You’re building an offline-first app with relational data (e.g., a note-taking app, CRM, or chat client).
  • You need to run complex queries or sort/filter large datasets.
  • You want to evolve your data model over time with safe migrations.

Use idb-keyval if:

  • You only need to store a few simple values (e.g., auth tokens, UI settings, feature flags).
  • You want the tiniest possible dependency with no setup.
  • You don’t care about querying or structure.

Use localforage if:

  • You’re replacing localStorage in an existing codebase and want minimal changes.
  • You need fallback support for environments where IndexedDB might be restricted.
  • Your data access patterns are strictly key-based with no need for queries.

📊 Summary Table

Featuredexieidb-keyvallocalforage
Data ModelTables with schemasFlat key-valueFlat 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 ForStructured, query-heavy appsSimple key-value cachinglocalStorage replacement

💬 Final Thought

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.

How to Choose: dexie vs idb-keyval vs localforage

  • dexie:

    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.

  • idb-keyval:

    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.

  • localforage:

    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.

README for dexie

Dexie.js

NPM Version Build Status Join our Discord

Dexie.js is a wrapper library for indexedDB - the standard database in the browser. https://dexie.org.

Why Dexie.js?

IndexedDB is the portable database for all browser engines. Dexie.js makes it fun and easy to work with.

But also:

  • Dexie.js is widely used by 100,000 of web sites, apps and other projects and supports all browsers, Electron for Desktop apps, Capacitor for iOS / Android apps and of course pure PWAs.
  • Dexie.js works around bugs in the IndexedDB implementations, giving a more stable user experience.
  • It's an easy step to make it sync.

Hello World (vanilla JS)

<!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.

Hello World (legacy script tags)

<!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>

Hello World (React + Typescript)

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

API Reference

Samples

Performance

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.

Supported operations

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

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/

Samples

https://dexie.org/docs/Samples

https://github.com/dexie/Dexie.js/tree/master/samples

Knowledge Base

https://dexie.org/docs/Questions-and-Answers

Website

https://dexie.org

Install via npm

npm install dexie

Download

For those who don't like package managers, here's the download links:

UMD (for legacy script includes as well as commonjs require):

https://unpkg.com/dexie@latest/dist/dexie.min.js

https://unpkg.com/dexie@latest/dist/dexie.min.js.map

Modern (ES module):

https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs

https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs.map

Typings:

https://unpkg.com/dexie@latest/dist/dexie.d.ts

Contributing

See CONTRIBUTING.md

Build

pnpm install
pnpm run build

Test

pnpm test

Watch

pnpm run watch

Browser testing via LAMDBATEST