Redux Storage Middleware

raw JSON →
1.1.292 verified Sat Apr 25 auth: no javascript

Redux Storage Middleware is a lightweight middleware for Redux that persists state to storage backends (e.g., localStorage) and rehydrates it on app load. Current stable version is 1.1.292. It is maintained by sequencemedia and requires Node >=18.12.0. It distinguishes itself from alternatives like redux-persist by being minimal, with no built-in transforms or migrations, and relies on the storage engine provided by the developer.

error Cannot find module 'redux-storage-middleware'
cause Package not installed or not in node_modules.
fix
Run npm install redux-storage-middleware
error The engine must be an object with getItem, setItem, removeItem methods
cause Provided engine does not implement the required interface.
fix
Ensure the engine object has getItem, setItem, removeItem functions.
breaking ESM only since v1.0.0; require() will not work.
fix Use import syntax and ensure your project is ESM or use a dynamic import.
gotcha Middleware must be applied before any other middleware that depends on state being persisted.
fix Ensure storageMiddleware is first in the middleware chain.
gotcha The storage engine must return Promises; synchronous engines like sync localStorage will cause errors if used directly.
fix Wrap sync operations in Promise.resolve() or use an async storage library.
npm install redux-storage-middleware
yarn add redux-storage-middleware
pnpm add redux-storage-middleware

Configures and applies redux-storage-middleware with a localStorage engine and custom serialization.

import storageMiddleware from 'redux-storage-middleware';
import { createStore, applyMiddleware } from 'redux';

const storageEngine = {
  getItem: (key) => Promise.resolve(localStorage.getItem(key)),
  setItem: (key, value) => Promise.resolve(localStorage.setItem(key, value)),
  removeItem: (key) => Promise.resolve(localStorage.removeItem(key)),
};

const middleware = storageMiddleware({
  engine: storageEngine,
  key: 'my-app-state',
  serialize: JSON.stringify,
  deserialize: JSON.parse,
});

const store = createStore(rootReducer, applyMiddleware(middleware));