localforage vs redux-persist vs redux-persist-transform-encrypt vs redux-persist-transform-filter
State Persistence and Storage Strategies in Redux Applications
localforageredux-persistredux-persist-transform-encryptredux-persist-transform-filterSimilar Packages:

State Persistence and Storage Strategies in Redux Applications

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
localforage025,767-2495 years agoApache-2.0
redux-persist012,998-5967 years agoMIT
redux-persist-transform-encrypt03627.31 kB02 years agoMIT
redux-persist-transform-filter019012.3 kB14-MIT

Building a Persistent Redux Store: Storage, Integration, and Security

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.

πŸ—„οΈ Storage Layer: Synchronous vs Asynchronous

redux-persist defaults to localStorage, which is synchronous and limited to about 5MB.

  • Blocking the main thread during save/load can cause jank in heavy apps.
  • Suitable for small settings or tokens.
// 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.

  • Non-blocking I/O keeps the UI smooth during large data saves.
  • Better for caching substantial amounts of structured data.
// 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
};

πŸ”’ Security Layer: Encryption Transforms

redux-persist-transform-encrypt sits between your state and the storage engine.

  • It encrypts data before it hits localStorage or IndexedDB.
  • Protects sensitive data from casual inspection in DevTools.
// 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.

  • Do not use for high-frequency state updates (like cursor position).
  • Ensure the secret key is not hardcoded in production if possible.

βœ‚οΈ Size Control: Filtering Transforms

redux-persist-transform-filter lets you pick exactly what gets saved.

  • Prevents bloating storage with transient UI state.
  • Speeds up rehydration by reducing payload size.
// 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.

  • Whitelist essential data (session, preferences).
  • Blacklist volatile data (modals, form drafts).

⚠️ Maintenance and Risk Assessment

redux-persist is widely adopted but development has slowed.

  • It is stable but not actively adding new features.
  • Suitable for long-term projects where stability matters more than new features.

redux-persist-transform-* packages are community-maintained.

  • They are not official addons and may lag behind core updates.
  • Verify activity on npm before adding to critical production paths.

localforage is mature but modern browsers now support IndexedDB natively.

  • Consider using native idb wrappers for new projects if you don't need legacy WebSQL support.
  • Still a safe choice for abstracting storage differences.

🧩 Putting It All Together

A robust persistence setup often combines all four tools.

  • redux-persist manages the lifecycle.
  • localforage handles the heavy lifting of storage.
  • Transforms secure and trim the data.
// 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);

πŸ“Š Summary: Roles and Responsibilities

PackageLayerPrimary RoleAsync Support
localforageStorageAbstracts IndexedDB/LocalStorageβœ… Yes
redux-persistIntegrationConnects Redux to Storageβœ… Yes
...-encryptSecurityEncrypts State Data❌ Sync Transform
...-filterOptimizationWhitelists State Keys❌ Sync Transform

πŸ’‘ Final Recommendation

redux-persist is the core requirement for most Redux apps needing persistence.

  • Start with the default localStorage for simplicity.
  • Switch to localforage if you hit storage limits or notice UI lag during saves.

Transforms should be added only when needed.

  • Use redux-persist-transform-filter early to keep storage clean.
  • Use redux-persist-transform-encrypt only for sensitive fields to avoid performance hits.

Final Thought: These tools are complementary, not competitive.

  • Build your storage strategy by layering them based on security and performance needs.
  • Always check the maintenance status of community transforms before committing.

How to Choose: localforage vs redux-persist vs redux-persist-transform-encrypt vs redux-persist-transform-filter

  • localforage:

    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.

  • redux-persist:

    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.

  • redux-persist-transform-encrypt:

    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.

  • redux-persist-transform-filter:

    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.

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