redux-broadcast-sync
v0.1.0
Published
Redux middleware to sync state across iframes and browser tabs via BroadcastChannel
Maintainers
Readme
redux-broadcast-sync
Redux middleware to sync state across iframes and browser tabs via the BroadcastChannel API.
- Syncs state deltas (not actions) — only what changed is broadcast
- Works across iframes, tabs, and any browsing context on the same origin
- New contexts receive the current state automatically on mount
- Per-sender sequence numbers prevent stale or out-of-order updates
- Configurable: channel name, debounce, excluded slices and actions
Installation
npm install redux-broadcast-sync@reduxjs/toolkit is a peer dependency — make sure it's installed in your project.
Setup
1. Wrap your root reducer
// store.ts
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import { createBroadcastMiddleware, createSyncableReducer } from "redux-broadcast-sync";
const rootReducer = combineReducers({
user: userReducer,
products: productsReducer,
});
const { middleware, cleanup } = createBroadcastMiddleware();
export const store = configureStore({
reducer: createSyncableReducer(rootReducer),
middleware: (getDefault) => getDefault().concat(middleware),
});
// HMR cleanup (Vite)
if (import.meta.hot) {
import.meta.hot.dispose(cleanup);
}2. Use Redux normally
No changes needed in your components or slices. Any dispatch() call will automatically sync the state delta to all other contexts sharing the same channelName.
API
createBroadcastMiddleware(options?)
Creates the middleware and returns { middleware, cleanup }.
| Option | Type | Default | Description |
|---|---|---|---|
| channelName | string | "redux-sync" | Name of the shared BroadcastChannel |
| debounceMs | number | 0 | Debounce delay before emitting a STATE_UPDATE |
| fallbackTimeoutMs | number | 50 | Timeout before a new context declares itself ready if no peer responds |
| excludeSlices | string[] | [] | State slices to exclude from sync (e.g. local UI state) |
| excludeActions | string[] | [] | Action types that will not trigger a sync (e.g. local-only actions) |
| excludeAction | (action) => boolean | undefined | Predicate to exclude actions dynamically — return true to skip sync |
| createChannel | (name: string) => BroadcastChannel | (name) => new BroadcastChannel(name) | Custom channel factory — use this to inject a polyfill |
| generateId | () => string | () => crypto.randomUUID() | Custom instance ID generator — useful when crypto.randomUUID is unavailable |
| maxPendingUpdates | number | 100 | Max STATE_UPDATEs buffered before INIT_RESPONSE — oldest are dropped if exceeded |
const { middleware, cleanup } = createBroadcastMiddleware({
channelName: "my-app",
excludeSlices: ["ui", "router"],
});createSyncableReducer(rootReducer)
Wraps your root reducer so it can receive state patches from other contexts.
const store = configureStore({
reducer: createSyncableReducer(rootReducer),
});SYNC_ACTION_TYPE
The internal action type used to apply incoming state patches ("@@BROADCAST_SYNC"). Useful if you need to filter it out in other middleware or redux-devtools.
How it works
Context A (iframe / tab) Context B (iframe / tab)
───────────────────────── ─────────────────────────
dispatch(addUser(...))
→ rootReducer updates state
→ shallowDiff detects delta
→ BroadcastChannel.postMessage
STATE_UPDATE { user: {...} }
→ handleStateUpdate()
→ dispatch(@@BROADCAST_SYNC)
→ syncableReducer merges delta
→ React re-rendersNew context initialization:
When a new context boots, it sends a REQUEST_STATE message. Any existing context responds with its full state (INIT_RESPONSE). If no peer responds within fallbackTimeoutMs (50ms by default), the context starts fresh with its own initial state.
Example: iframes with shared Redux state
// Each iframe creates its own store with the same setup.
// State stays in sync across all of them automatically.
// iframe-a/store.ts
const { middleware } = createBroadcastMiddleware({ channelName: "app" });
export const store = configureStore({
reducer: createSyncableReducer(rootReducer),
middleware: (get) => get().concat(middleware),
});
// iframe-b/store.ts — identical setup, different React tree
const { middleware } = createBroadcastMiddleware({ channelName: "app" });
export const store = configureStore({
reducer: createSyncableReducer(rootReducer),
middleware: (get) => get().concat(middleware),
});Excluding local state
Use excludeSlices to prevent entire state slices from being broadcast to other contexts:
createBroadcastMiddleware({
excludeSlices: ["ui", "notifications", "router"],
});Use excludeActions to prevent specific actions from triggering a sync — the action still runs through the reducer locally, but the resulting state delta is not broadcast:
createBroadcastMiddleware({
excludeActions: ["ui/setHoveredRow", "ui/openDropdown"],
});Use excludeAction for dynamic filtering with a predicate — useful when a list of strings isn't expressive enough:
createBroadcastMiddleware({
// Exclude an entire feature by prefix
excludeAction: (action) => action.type.startsWith("ui/"),
});
createBroadcastMiddleware({
// Exclude based on payload
excludeAction: (action) => action.type === "items/select" && action.payload.temporary,
});Both excludeActions and excludeAction can be used together — an action is excluded if either matches.
Browser support
Requires the BroadcastChannel API — supported in all modern browsers. Not available in Web Workers or Service Workers without a polyfill.
To use in environments without native BroadcastChannel support (e.g. Web Workers, older browsers), inject a polyfill via the createChannel option:
import { BroadcastChannel } from "broadcast-channel";
createBroadcastMiddleware({
createChannel: (name) => new BroadcastChannel(name),
});