Cross-Tab Sync
Sync state across browser tabs using BroadcastChannel (with localStorage fallback).
Quick Setup
ts
import { tabSyncPlugin } from "statemesh-core/sync";
mesh.use(tabSyncPlugin({
keys: ["theme", "cart"],
channel: "my-app-state",
strategy: "latest-wins"
}));| Option | Type | Default | Description |
|---|---|---|---|
keys | string[] | Required | State paths to sync |
channel | string | "statemesh-sync" | BroadcastChannel name |
strategy | "latest-wins" | "merge" | "latest-wins" | Conflict resolution strategy |
debounce | number | 50 | Debounce sync messages in ms |
How It Works
- When a synced path changes, the plugin sends a message to other tabs
- Other tabs receive the message and apply the change
- Each message includes a source tab ID to prevent loops
- Messages are validated against the whitelist before applying
Transports
BroadcastChannel (Default)
ts
import { createBroadcastChannelTransport } from "statemesh-core/sync";
const transport = createBroadcastChannelTransport("my-app-channel");localStorage Fallback
ts
import { createLocalStorageSyncTransport } from "statemesh-core/sync";
const transport = createLocalStorageSyncTransport("my-app-storage-key");localStorage fallback works in browsers that don't support BroadcastChannel. It uses storage events to detect changes.
Strategy
| Strategy | Behavior |
|---|---|
latest-wins | The most recent message overwrites local state |
merge | Merge incoming changes with local state |
Important Notes
TIP
Each message includes a source tab ID to prevent echo loops. Changes from the current tab are ignored.
WARNING
Only sync non-sensitive state. Cross-tab sync uses BroadcastChannel or localStorage, which are accessible to any script on the same origin.
TIP
Messages are validated against the whitelist. Only keys listed in keys are synced.
Next Steps
- Persistence — Persist state across sessions
- DevTools — In-app DevTools
