Skip to main content

Middleware

Middleware observes every action after it’s reduced and can produce additional effects. Use middleware for cross-cutting concerns that shouldn’t live inside the reducer — logging, analytics, persistence, crash reporting.

PrismMiddleware Protocol

Protocol Definition
The middleware receives the post-reduction state and the action that was dispatched. It returns an effect that can dispatch further actions.

Custom Middleware

Logging Middleware

Attaching to a Store

Pass middleware as the third argument when creating a store:
Store with Middleware
Or compose it with the reducer directly:

PrismSideEffect

PrismSideEffect is a closure-based middleware. Use it when you don’t need a dedicated type:
Inline Side Effect

.none

A no-op side effect that always returns .none:

.combine

Merge multiple side effects into one. All run concurrently for each action:
Combined Middleware

Practical Examples

Analytics Middleware

Track specific user interactions without polluting reducer logic:
Analytics Middleware

Persistence Middleware

Auto-save state to disk after certain actions:
Persistence Middleware

Error Reporting Middleware

Capture errors globally:
Error Reporting
Middleware runs after the reducer. The state parameter already reflects the changes from the current action. This means you can react to the new state, not the old one.

Middleware vs. Effects