{"id":17486,"library":"alveron-middleware-persistence","title":"Alveron Middleware Persistence","description":"Alveron Middleware Persistence is a specialized middleware designed to integrate a state persistence layer into Alveron applications. Alveron is a lightweight, Elm-inspired state management library for React (approx. 1.2kb) that leverages React's `useState` hook and handles asynchronous side effects. This middleware enables Alveron stores to automatically persist their state to browser storage mechanisms like `localStorage` or `sessionStorage`, ensuring that application data endures across page reloads or browser sessions. The current stable version, 8.0.3, is designed to work seamlessly with Alveron versions greater than 8.0.0. While a specific release cadence for this middleware is not publicly documented, its versioning typically aligns with major releases of the core `alveron` library. Its primary differentiator is its direct compatibility and integration within the Alveron ecosystem, providing a structured approach to state hydration and rehydration tailored for Alveron's model, actions, and effects architecture.","status":"active","version":"8.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/robinweser/alveron","tags":["javascript","alveron","middleware","persistance","localStorage","sessionStorage","typescript"],"install":[{"cmd":"npm install alveron-middleware-persistence","lang":"bash","label":"npm"},{"cmd":"yarn add alveron-middleware-persistence","lang":"bash","label":"yarn"},{"cmd":"pnpm add alveron-middleware-persistence","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for Alveron state management functionality.","package":"alveron","optional":false}],"imports":[{"note":"The library primarily uses ESM exports. Use named imports if specific utility functions are also exported.","wrong":"const persistenceMiddleware = require('alveron-middleware-persistence');","symbol":"persistenceMiddleware","correct":"import persistenceMiddleware from 'alveron-middleware-persistence';"},{"note":"Type import for configuring the middleware (if exported, otherwise define inline).","symbol":"PersistenceConfig","correct":"import persistenceMiddleware, { PersistenceConfig } from 'alveron-middleware-persistence';"}],"quickstart":{"code":"import * as React from 'react';\nimport { useStoreWithMiddleware, Middleware } from 'alveron';\nimport persistenceMiddleware from 'alveron-middleware-persistence';\n\ninterface Model {\n  count: number;\n  lastUpdate: string;\n}\n\ninterface Actions {\n  increment: (amount?: number) => Model;\n  decrement: (amount?: number) => Model;\n}\n\nconst initialModel: Model = {\n  count: 0,\n  lastUpdate: new Date().toISOString(),\n};\n\nconst actions = {\n  increment: (amount: number = 1) => (prevState: Model) => [\n    { ...prevState, count: prevState.count + amount, lastUpdate: new Date().toISOString() },\n  ],\n  decrement: (amount: number = 1) => (prevState: Model) => [\n    { ...prevState, count: prevState.count - amount, lastUpdate: new Date().toISOString() },\n  ],\n};\n\n// Define persistence configuration\nconst persistenceConfig = {\n  key: 'my-alveron-app-state', // Unique key for localStorage\n  storage: localStorage, // or sessionStorage\n  // Optional: only persist `count`, not `lastUpdate`\n  partialize: (state: Model) => ({ count: state.count }),\n};\n\nconst persistedCounterMiddleware: Middleware<Model, Actions> = persistenceMiddleware(persistenceConfig);\n\nfunction Counter() {\n  const [state, { increment, decrement }] = useStoreWithMiddleware(\n    actions,\n    initialModel,\n    [persistedCounterMiddleware]\n  );\n\n  return (\n    <div>\n      <h1>Count: {state.count}</h1>\n      <p>Last updated: {new Date(state.lastUpdate).toLocaleTimeString()}</p>\n      <button onClick={() => increment()}>Increment</button>\n      <button onClick={() => decrement()}>Decrement</button>\n      <button onClick={() => localStorage.clear()}>Clear Storage</button>\n      <p>Refresh the page to see the count persist!</p>\n    </div>\n  );\n}\n\nfunction App() {\n  return (\n    <React.StrictMode>\n      <Counter />\n    </React.StrictMode>\n  );\n}\n\nexport default App;\n","lang":"typescript","description":"This example demonstrates how to integrate `alveron-middleware-persistence` with an Alveron store to persist and rehydrate a simple counter's state using `localStorage`. It shows the basic setup of an Alveron store with actions and how to apply the configured persistence middleware."},"warnings":[{"fix":"Review the official Alveron and alveron-middleware-persistence documentation for migration guides and updated API usage when upgrading major versions.","message":"Major version updates (e.g., from v7 to v8) typically introduce breaking changes, often related to underlying Alveron API changes or persistence configuration format. Consult Alveron's changelog and this middleware's documentation for migration steps.","severity":"breaking","affected_versions":">=8.0.0"},{"fix":"Implement a versioning strategy within your persistence configuration (if supported by the library) and provide migration functions. For development, manually clear browser storage (`localStorage.clear()`) after schema changes. For production, consider user-data migration strategies or default fallbacks for undefined properties.","message":"Changes to the shape of your persisted state (e.g., adding/removing properties, changing data types) can lead to hydration errors or unexpected behavior if old, incompatible data exists in `localStorage` or `sessionStorage`. Users' browsers might hold stale data from previous versions of your application.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure the middleware is only executed in browser contexts, or provide global polyfills for `localStorage` and `sessionStorage` (e.g., using `node-localstorage` or a mock) for SSR or Node.js testing environments.","message":"This middleware is designed for browser environments using `localStorage` or `sessionStorage`. Attempting to use it directly in a Node.js environment (e.g., for Server-Side Rendering) without appropriate polyfills for these browser APIs will result in runtime errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Wrap your Alveron store initialization with a check for `typeof window !== 'undefined'` or provide `localStorage` / `sessionStorage` polyfills for Node.js environments.","cause":"Attempting to use the middleware in a Node.js environment (e.g., SSR) where `localStorage` or `sessionStorage` are not defined.","error":"Uncaught TypeError: Cannot read properties of undefined (reading 'getItem')"},{"fix":"For ESM, use `import persistenceMiddleware from 'alveron-middleware-persistence';`. For CommonJS (if supported), ensure correct interop or use a bundler that handles ESM imports correctly.","cause":"Incorrect CommonJS `require()` usage for an ESM-first package or incorrect named vs default import syntax in an ESM context.","error":"TypeError: (0 , _alveron_middleware_persistence__WEBPACK_IMPORTED_MODULE_1__.default) is not a function"},{"fix":"Install or upgrade Alveron: `npm install alveron@'>8.0.0'` or `yarn add alveron@'>8.0.0'`.","cause":"The peer dependency `alveron` is missing or an incompatible version is installed.","error":"Error: Alveron: useStoreWithMiddleware expects the 'alveron' library to be installed. Please ensure it's in your dependencies."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}