localforage vs idb-keyval vs dexie
クライアントサイドストレージ向け IndexedDB ライブラリの比較
localforageidb-keyvaldexie類似パッケージ:

クライアントサイドストレージ向け IndexedDB ライブラリの比較

dexieidb-keyvallocalforage はいずれもブラウザの IndexedDB をより使いやすくするための JavaScript ライブラリです。IndexedDB は強力なクライアントサイドデータベースですが、低レベルで冗長な API のため、これらのライブラリは開発者の生産性を高めることを目的としています。dexie はフル機能のクエリエンジンとトランザクション制御を備えた ORM に近い設計です。idb-keyval は単純な key-value ストアとして動作し、最小限の API で即座に利用できます。localforage は localStorage に似たインターフェースを提供しつつ、バックエンドに IndexedDB(または WebSQL / localStorage)を使用することで、非同期かつ大容量のストレージを実現します。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
localforage5,394,22425,767-2495年前Apache-2.0
idb-keyval3,305,1403,160928 kB2510ヶ月前Apache-2.0
dexie922,61814,1243.09 MB5893ヶ月前Apache-2.0

クライアントサイドストレージ向け IndexedDB ライブラリの深掘り比較

dexieidb-keyvallocalforage はすべて IndexedDB をラップして使いやすくするライブラリですが、設計思想と用途が大きく異なります。それぞれの特徴を、実際のコードを交えて詳しく見ていきましょう。

🗃️ データモデル:柔軟なスキーマ vs 単純な key-value

dexie は明示的なテーブル定義とスキーマを持つ、本格的なデータベースライクな設計です。

  • 複数のテーブルを定義でき、各テーブルにプライマリキーとインデックスを設定可能
  • 関係性(外部キー)こそ直接サポートしませんが、柔軟なクエリで代替可能
// dexie: テーブルとインデックスの定義
import Dexie from 'dexie';

const db = new Dexie('MyApp');
db.version(1).stores({
  friends: '++id, name, age', // 自動インクリメントID、name と age にインデックス
  notes: '++id, title, &body' // body にユニークインデックス
});

idb-keyval は完全な key-value ストアで、1 つのストア内に任意のキーと値を保存します。

  • テーブルやスキーマの概念は一切なく、単一の名前空間
  • 値は任意の JavaScript オブジェクト(structured clone 可能なもの)
// idb-keyval: スキーマ不要、即時使用
import { get, set } from 'idb-keyval';

await set('user', { name: 'Alice', age: 30 });
const user = await get('user');

localforage も key-value モデルですが、複数の「インスタンス」で名前空間を分離できます。

  • 各インスタンスは独立したストアとして動作
  • ただし、各キー内の値は単一オブジェクトであり、ネストされたクエリは不可
// localforage: 名前付きインスタンス
import localforage from 'localforage';

const userStore = localforage.createInstance({ name: 'users' });
await userStore.setItem('alice', { age: 30 });
const alice = await userStore.getItem('alice');

🔍 クエリ能力:高度な検索 vs 単純取得

dexie は豊富なクエリメソッドを提供します。

  • 範囲検索(between)、部分一致(startsWith)、複合条件(and/or)など
  • インデックスを利用した高速検索
// dexie: 複雑なクエリ
const adults = await db.friends
  .where('age')
  .above(18)
  .toArray();

const names = await db.friends
  .where('name')
  .startsWith('A')
  .keys();

idb-keyval はキーによる直接取得のみをサポートします。

  • 全件取得(values())やキー一覧(keys())は可能だが、フィルタリングは自前実装
  • クエリという概念は存在しない
// idb-keyval: キー指定での取得のみ
import { get, keys } from 'idb-keyval';

const user = await get('user-123');
// 条件検索はできない

localforage も同様に、キーによる取得と全件取得のみ。

  • keys() で全キーを取得後、自前でフィルタリングする必要あり
  • インデックスや範囲検索の機能はない
// localforage: キーによる取得
const user = await localforage.getItem('user-123');
// 複雑な検索は不可能

⚙️ トランザクションと一貫性

dexie は明示的なトランザクション制御をサポートします。

  • 複数テーブルにまたがる操作をアトミックに実行可能
  • 読み取り専用 or 読み書きモードを指定
// dexie: トランザクション
await db.transaction('rw', db.friends, db.notes, async () => {
  await db.friends.add({ name: 'Bob' });
  await db.notes.add({ title: 'Note for Bob' });
});

idb-keyvallocalforage はトランザクションを公開していません。

  • 各操作は内部で個別にトランザクションされるが、複数操作の一貫性は保証されない
  • 同時実行時の競合状態に注意が必要
// idb-keyval / localforage: トランザクションなし
await set('a', 1);
await set('b', 2);
// この2操作はアトミックではない

🔄 非同期 API のスタイル

dexie は Promise ベースで、チェーン可能なクエリビルダーを提供します。

  • 現代的な async/await と相性が良い
// dexie: Promise チェーン
const result = await db.friends
  .where('age')
  .above(25)
  .sortBy('name');

idb-keyval も Promise 専用で、極めてシンプルな関数群です。

  • コールバックはサポートせず、Promise または async/await のみ
// idb-keyval: 単純な Promise 関数
const value = await get('key');

localforage は Promise とコールバックの両方をサポートします。

  • 古いコードベースへの移行を考慮した設計
// localforage: 両方のスタイル
// Promise
const value = await localforage.getItem('key');

// コールバック
localforage.getItem('key', (err, value) => {
  if (!err) console.log(value);
});

🌐 バックエンドと互換性

dexieidb-keyval は IndexedDB にのみ依存します。

  • 現代のブラウザでは問題ないが、古い環境(IE)では動作しない
  • ただし、IndexedDB の機能をフル活用できる

localforage は複数のストレージバックエンドを自動で切り替えます。

  • IndexedDB → WebSQL → localStorage の順で降格
  • 古いブラウザでも動作するが、機能が制限される可能性あり
// localforage: バックエンド自動選択
// 開発者は意識する必要なし

📦 実際の使用シーン別推奨

シナリオ1: オフライン対応の TODO アプリ

  • 複数のリスト、タグ、優先度などでフィルタリングが必要
  • 推奨: dexie
  • 理由: インデックスを使った高速フィルタリングと、複数テーブル間の整合性確保が可能
// dexie での例
db.version(1).stores({
  todos: '++id, listId, completed, priority',
  lists: '++id, name'
});

// 高優先度の未完了タスクを取得
const highPriority = await db.todos
  .where('priority')
  .equals('high')
  .and(todo => !todo.completed)
  .toArray();

シナリオ2: 設定や認証トークンの保存

  • 単純な key-value で十分、複雑なクエリは不要
  • 推奨: idb-keyval
  • 理由: 軽量で、必要な機能だけを提供。bundle size への影響も最小
// idb-keyval での例
await set('authToken', 'abc123');
const token = await get('authToken');

シナリオ3: 既存の localStorage コードを非同期化

  • 既に localStorage.setItem で書かれたコードがある
  • 大量データ保存で QuotaExceededError が発生
  • 推奨: localforage
  • 理由: API がほぼ同じで、簡単に置き換え可能。古いブラウザ対応も維持
// localforage での置き換え
// localStorage.setItem('user', JSON.stringify(user));
await localforage.setItem('user', user); // シリアライズ不要

📊 まとめ:選択のポイント

特徴dexieidb-keyvallocalforage
データモデルテーブル+インデックス単一 key-valuekey-value(名前空間可)
クエリ能力高度(範囲、部分一致等)キー取得のみキー取得のみ
トランザクション明示的サポートなしなし
API スタイルPromise + チェーンPromise 関数Promise + コールバック
バックエンドIndexedDB のみIndexedDB のみIndexedDB/WebSQL/localStorage
bundle sizeやや大きめ極小中程度

💡 最終的な判断基準

  • 複雑なデータ操作や検索が必要?dexie
  • 単純な保存/読み込みだけで十分?idb-keyval
  • localStorage 互換性や古いブラウザ対応が必須?localforage

これら3つのライブラリは、それぞれ異なる「痛み」を解決するために作られています。自分のプロジェクトが抱える課題に最もフィットするものを選ぶことが、長期的なメンテナンス性と開発速度の鍵になります。

選び方: localforage vs idb-keyval vs dexie

  • localforage:

    localforage は既存の localStorage コードを非同期かつ大容量対応に置き換えたい場合に最適です。コールバックと Promise の両方をサポートし、バックエンドを自動で切り替えるため、古いブラウザとの互換性も考慮できます。ただし、IndexedDB の高度な機能(カスタムインデックス、複雑なクエリ)は利用できません。

  • idb-keyval:

    idb-keyval は「ただ値を保存して取り出したい」だけのケースに最適です。API が localStorage に似ており、わずか 4 つの関数(getsetdelclear)しか持たないため、導入・理解が極めて容易です。複雑なクエリやスキーマ管理は不要で、軽量さとシンプルさを重視するプロジェクトに適しています。

  • dexie:

    dexie は複雑なクエリ(範囲検索、インデックス、複合キーなど)やトランザクション制御が必要なアプリケーションに最適です。オフラインファーストの PWA や大量の構造化データを扱う場合に強みを発揮します。ただし、学習コストがやや高く、シンプルな key-value 用途にはオーバーキルになる可能性があります。

localforage のREADME

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