Skip to content

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"
}));
OptionTypeDefaultDescription
keysstring[]RequiredState paths to sync
channelstring"statemesh-sync"BroadcastChannel name
strategy"latest-wins" | "merge""latest-wins"Conflict resolution strategy
debouncenumber50Debounce sync messages in ms

How It Works

  1. When a synced path changes, the plugin sends a message to other tabs
  2. Other tabs receive the message and apply the change
  3. Each message includes a source tab ID to prevent loops
  4. 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

StrategyBehavior
latest-winsThe most recent message overwrites local state
mergeMerge 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

Released under the MIT License.