localforage vs idb-keyval vs dexie
Client-Side Storage Libraries for Web Applications
localforageidb-keyvaldexieSimilar 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
localforage5,953,11225,750-2494 years agoApache-2.0
idb-keyval3,369,5353,146928 kB259 months agoApache-2.0
dexie1,001,31514,0353.09 MB5932 months 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: localforage vs idb-keyval vs dexie
  • 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.

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

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

README for localforage

localForage

Build Status NPM version Dependency Status npm jsDelivr Hits minzipped size

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

Support

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.

How to use localForage

Callbacks vs Promises

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.

Storing Blobs, TypedArrays, and other JS objects

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.

Configuration

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().

Multiple instances

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");

RequireJS

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);
});

TypeScript

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");

Framework Support

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.

Custom Drivers

You can create your own driver if you want; see the defineDriver API docs.

There is a list of custom drivers on the wiki.

Working on localForage

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!

Running Tests

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.

Library Size

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:

minified
`~29kB`
gzipped
`~8.8kB`
brotli'd
`~7.8kB`

License

This program is free software; it is distributed under an Apache License.


Copyright (c) 2013-2016 Mozilla (Contributors).