Redux Cookies Middleware

0.2.1 · abandoned · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `redux-cookies-middleware` to persist specific parts of the Redux state ('auth.token' and 'session') into browser cookies, and how to hydrate the initial state from those cookies upon application load.

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.

view raw JSON →