Redux Cookies Middleware
Redux Cookies Middleware is a specialized Redux middleware designed to synchronize specific parts of a Redux state tree with browser cookies. Developers configure `paths` to indicate which state subsets, using dot-notation, should be persisted, along with their corresponding cookie names. It also offers `getStateFromCookies` to hydrate the initial Redux state from existing cookies, ensuring state continuity across sessions. The current stable version is 0.2.1. However, the project appears to be abandoned, with its last commit occurring in November 2018 and no significant updates since, which means it likely does not support modern Redux Toolkit patterns or ESM-only environments directly. Its primary differentiation lies in its explicit, configurable mapping of state paths to individual cookies, offering fine-grained control over what data is stored on the client side.
Common errors
-
Redux state is unexpectedly mutated after initial load during hydration from cookies.
cause Prior to v0.2.0, `getStateFromCookies` could directly mutate the `initialState` object passed to it when merging cookie data.fixUpgrade to `redux-cookies-middleware` v0.2.0 or higher to utilize the fixed, non-mutating `getStateFromCookies` implementation. -
SyntaxError: Unexpected token <character> in JSON at position <number> when reading cookies.
cause `redux-cookies-middleware` attempted to JSON parse cookie values that were not valid JSON strings (e.g., simple strings or corrupted data), leading to parsing errors.fixUpgrade to `redux-cookies-middleware` v0.2.0 or higher, which includes improved error handling and robustness when attempting to parse potentially malformed JSON cookie values.
Warnings
- breaking The `redux-cookies-middleware` project appears to be abandoned, with no commits since November 2018. This means it may not be compatible with newer versions of React, Redux, or modern JavaScript build toolchains (e.g., ESM-only environments). Consider using a more actively maintained state persistence library.
- gotcha Version 0.2.0 introduced a 'full re-write' of the `getStoreFromCookies` API. Although noted as 'non breaking', significant internal changes can sometimes lead to subtle behavioral differences or edge-case regressions not immediately apparent.
- gotcha The library explicitly uses dot-notation strings to define paths for state serialization. This pattern can be fragile if your Redux state shape frequently changes or if refactoring renames deeply nested keys.
- gotcha The `paths` configuration allows custom `equalityCheck` and `deleteCheck` functions. If these functions are not robust or introduce side effects, they could lead to unexpected cookie updates or deletions, or performance issues.
Install
-
npm install redux-cookies-middleware -
yarn add redux-cookies-middleware -
pnpm add redux-cookies-middleware
Imports
- reduxCookiesMiddleware
const reduxCookiesMiddleware = require('redux-cookies-middleware');import reduxCookiesMiddleware from 'redux-cookies-middleware';
- getStateFromCookies
const getStateFromCookies = require('redux-cookies-middleware/getStateFromCookies');import getStateFromCookies from 'redux-cookies-middleware/getStateFromCookies';
- Paths Configuration Object
const paths = { 'auth.token': { name: 'my_app_token' } };
Quickstart
import { applyMiddleware, createStore, compose } from 'redux';
import reduxCookiesMiddleware from 'redux-cookies-middleware';
import getStateFromCookies from 'redux-cookies-middleware/getStateFromCookies';
// A dummy reducer for demonstration purposes
const reducer = (state = {}, action) => {
switch (action.type) {
case 'SET_AUTH_TOKEN':
return { ...state, auth: { ...state.auth, token: action.payload } };
case 'SET_SESSION':
return { ...state, session: action.payload };
default:
return state;
}
};
// Initial state structure
let initialState = {
auth: {
token: null,
key: 'some_key'
},
session: null
};
// Define which parts of the state to persist in cookies and their cookie names
const paths = {
'auth.token': { name: 'my_app_token' },
'session': { name: 'my_app_session', httpOnly: false, secure: process.env.NODE_ENV === 'production' }
};
// Read stored data from cookies and merge it with the initial state
// This should happen before creating the store to ensure initial state is hydrated.
initialState = getStateFromCookies(initialState, paths);
// Create Redux store with the middleware
const store = createStore(
reducer,
initialState,
applyMiddleware(reduxCookiesMiddleware(paths))
);
// Example dispatch to demonstrate persistence
store.dispatch({ type: 'SET_AUTH_TOKEN', payload: 'new-auth-token-123' });
store.dispatch({ type: 'SET_SESSION', payload: 'user-session-abc' });
console.log('Store state after dispatches:', store.getState());
// In a browser, you would now see 'my_app_token' and 'my_app_session' cookies.
// For Node.js, this example would require a cookie-aware environment or mocking.