localforage provides an asynchronous storage interface for browsers, supporting IndexedDB, WebSQL, and localStorage. redux-persist integrates persistence directly into the Redux workflow, saving state automatically between sessions. redux-persist-transform-encrypt and redux-persist-transform-filter are addon transforms for redux-persist that handle security encryption and state slicing respectively. Together, they form a layered architecture for managing offline data in complex web apps.
When architecting a Redux application that needs to survive page reloads, you are not choosing a single library but rather assembling a stack. localforage, redux-persist, and its transform plugins each solve a specific layer of the persistence problem. Let's break down how they fit together and where the trade-offs lie.
redux-persist defaults to localStorage, which is synchronous and limited to about 5MB.
// redux-persist default storage (localStorage)
import storage from 'redux-persist/lib/storage';
const persistConfig = {
key: 'root',
storage: storage,
};
localforage uses IndexedDB under the hood, offering asynchronous access and much larger quotas.
// localforage standalone usage
import localforage from 'localforage';
await localforage.setItem('user', { id: 1, name: 'Alice' });
const user = await localforage.getItem('user');
Integration: You can combine them. redux-persist accepts any storage engine that matches its interface. localforage can act as the engine for redux-persist.
// Using localforage as redux-persist storage
import localforage from 'localforage';
import { persistReducer } from 'redux-persist';
const persistConfig = {
key: 'root',
storage: localforage, // Async storage engine
};
redux-persist-transform-encrypt sits between your state and the storage engine.
localStorage or IndexedDB.// redux-persist-transform-encrypt
import createEncryptor from 'redux-persist-transform-encrypt';
const encryptor = createEncryptor({
secretKey: 'my-secret-key',
salt: 'my-salt',
});
const persistConfig = {
key: 'root',
storage: storage,
transforms: [encryptor],
};
Trade-off: Encryption adds CPU cost during every save and load.
redux-persist-transform-filter lets you pick exactly what gets saved.
// redux-persist-transform-filter
import createFilter from 'redux-persist-transform-filter';
const saveOnlyAuth = createFilter('auth', ['token', 'user']);
const persistConfig = {
key: 'root',
storage: storage,
transforms: [saveOnlyAuth],
};
Trade-off: If you filter out too much, users lose context on reload.
redux-persist is widely adopted but development has slowed.
redux-persist-transform-* packages are community-maintained.
localforage is mature but modern browsers now support IndexedDB natively.
idb wrappers for new projects if you don't need legacy WebSQL support.A robust persistence setup often combines all four tools.
redux-persist manages the lifecycle.localforage handles the heavy lifting of storage.// Combined architecture example
import { persistStore, persistReducer } from 'redux-persist';
import localforage from 'localforage';
import createEncryptor from 'redux-persist-transform-encrypt';
import createFilter from 'redux-persist-transform-filter';
const encryptor = createEncryptor({ secretKey: 'secret' });
const filter = createFilter('auth', ['token']);
const persistConfig = {
key: 'root',
storage: localforage,
transforms: [encryptor, filter],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({ reducer: persistedReducer });
export const persistor = persistStore(store);
| Package | Layer | Primary Role | Async Support |
|---|---|---|---|
localforage | Storage | Abstracts IndexedDB/LocalStorage | β Yes |
redux-persist | Integration | Connects Redux to Storage | β Yes |
...-encrypt | Security | Encrypts State Data | β Sync Transform |
...-filter | Optimization | Whitelists State Keys | β Sync Transform |
redux-persist is the core requirement for most Redux apps needing persistence.
localforage if you hit storage limits or notice UI lag during saves.Transforms should be added only when needed.
redux-persist-transform-filter early to keep storage clean.redux-persist-transform-encrypt only for sensitive fields to avoid performance hits.Final Thought: These tools are complementary, not competitive.
Choose localforage when you need a promise-based storage API that abstracts away the differences between IndexedDB, WebSQL, and localStorage. It is ideal if you require larger storage quotas than localStorage allows or need non-blocking I/O operations. Use this as the storage engine backend for redux-persist instead of the default synchronous localStorage.
Choose redux-persist when you want to automatically save and rehydrate your Redux store without writing boilerplate code for every action. It is the standard solution for keeping user sessions, preferences, or cached data alive across page reloads. Select this if your app relies heavily on Redux for state management and needs a reliable persistence layer.
Choose redux-persist-transform-encrypt if you are storing sensitive information like tokens or personal data in the browser storage. It ensures that the persisted data is encrypted before writing and decrypted upon rehydration. Use this only when security requirements demand protection against local data inspection, as it adds computational overhead.
Choose redux-persist-transform-filter when you need to whitelist or blacklist specific parts of your Redux state for persistence. This is critical for avoiding storage bloat by excluding transient data like UI flags or large cached lists. Use this to keep your storage footprint small and improve rehydration 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).