zustand-sync-tabs is a lightweight (~1KB minzipped) middleware for Zustand that facilitates seamless state synchronization across multiple browser tabs, windows, and iframes, provided they share the same origin. The current stable version is 0.2.3. It offers a 'fire and forget' setup, making it ideal for single-user applications that need consistent state across browsing contexts. Key differentiators include its small bundle size, full TypeScript support, and robust handling of one-writer/many-reader scenarios. It leverages the Broadcast Channel API (or localStorage fallback) for communication and supports both full and partial state sharing via include/exclude options for specific fields.
npm install zustand-sync-tabsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate `zustand-sync-tabs` middleware with a Zustand store. It shows a basic store definition, the application of `syncTabs` middleware with a channel name, and how to optionally exclude specific fields from synchronization. The store's `count` will sync across tabs, while `text` will remain local.
Replace `regExpToIgnore: /pattern/` with `exclude: [/pattern/]` or `exclude: ['fieldName']` in your `syncTabs` options.
Ensure all browsing contexts requiring synchronization are hosted on the exact same origin (protocol, host, and port).
For persistence and cross-tab sync, consider using `persist-and-sync` or carefully test the order of middleware application. A common pattern is `create(persist(syncTabs(...)))` or `create(syncTabs(persist(...)))` depending on desired interaction, but using a dedicated solution might be simpler.
Ensure `syncTabs` wraps your store's `(set) => ({ ... })` definition correctly, e.g., `create(syncTabs(set => ({ ... }), { name: '...' }))`.Verify that the `name` property in the `syncTabs` options is an exact match (case-sensitive) for all instances of your store across different tabs. Also, confirm that all tabs are on the 'same origin'.