tab-sync-lite
v0.1.0
Published
Sync any store (Zustand, Redux, signals, useState, plain objects) across open browser tabs in one line. New tabs get the current state. Zero dependencies, any framework.
Maintainers
Readme
tab-sync-lite
Sync any store (Zustand, Redux, signals, useState, a plain object) across open browser tabs in one line. New tabs start with the current state. Zero dependencies, any framework.
Why tab-sync-lite?
A user logs out in one tab, and the other five tabs still look logged in. They switch to dark mode, and the other tabs stay light. They add to the cart, and the cart in the next tab is stale.
The browser's BroadcastChannel can pass messages between tabs, but it leaves the hard parts to you. tab-sync-lite does them:
- 🔌 Plugs into your store. Anything with
get,setandsubscribe. Zustand fits as is. - 🆕 New tabs catch up. A tab that just opened asks the open tabs for the current state and starts with it, instead of its defaults.
- 🔁 No echo loops. A tab never sends back a change it just received, with two tabs or twenty.
- 🧩 Works with any framework. React hook included. Vue, Svelte, Angular and plain JavaScript in a few lines.
- 🪶 Tiny. About 0.5 kB minified and gzipped, with zero dependencies.
- 🔷 TypeScript. Types are included.
Use cases
- 🚪 Log out everywhere: log out in one tab, every tab logs out.
- 🌗 Settings: theme, language and layout follow the user from tab to tab.
- 🛒 Carts and drafts: the cart in every tab shows the same items.
- 🔔 Counters: unread counts and "seen" flags stay in step.
Installation
npm install tab-sync-liteQuick start
import { tabsync } from 'tab-sync-lite';
const stop = tabsync('cart', {
get: store.getState,
set: store.setState,
subscribe: store.subscribe,
});Every tab that calls tabsync with the same name shares that store. Tabs only talk to tabs of the same site (same origin), and nothing leaves the browser.
Framework guides
React
import { useState } from 'react';
import { useTabSync } from 'tab-sync-lite/react';
function ThemeToggle() {
const [theme, setTheme] = useTabSync('theme', useState('light'));
const toggle = () => setTheme(theme === 'light' ? 'dark' : 'light');
return <button onClick={toggle}>{theme}</button>;
}useTabSync takes a [state, setState] pair and returns it unchanged, so it also works with other hooks that return a value and a setter, like useLocalStorage.
Zustand
import { create } from 'zustand';
import { tabsync } from 'tab-sync-lite';
export const useCart = create((set) => ({
items: [],
add: (item) => set((s) => ({ items: [...s.items, item] })),
}));
tabsync('cart', { get: useCart.getState, set: useCart.setState, subscribe: useCart.subscribe });Actions are functions, so they don't travel. Each tab keeps its own, and only the data is synced.
Redux
Redux has no setState, so add one action that replaces the state:
const reducer = (state, action) => (action.type === 'tabsync/replace' ? action.state : appReducer(state, action));
const store = createStore(reducer);
tabsync('app', {
get: store.getState,
set: (state) => store.dispatch({ type: 'tabsync/replace', state }),
subscribe: store.subscribe,
});Vue
const cart = ref([]);
let stop;
onMounted(() => {
stop = tabsync('cart', {
get: () => cart.value,
set: (value) => (cart.value = value),
subscribe: (listener) => watch(cart, listener, { deep: true }),
});
});
onUnmounted(() => stop());Svelte
import { writable, get } from 'svelte/store';
export const cart = writable([]);
tabsync('cart', { get: () => get(cart), set: cart.set, subscribe: cart.subscribe });Angular
@Injectable({ providedIn: 'root' })
export class CartService {
readonly items = signal<string[]>([]);
constructor() {
tabsync('cart', {
get: () => this.items(),
set: (value) => this.items.set(value),
subscribe: (listener) => {
const ref = effect(() => (this.items(), listener()));
return () => ref.destroy();
},
});
}
}Plain JavaScript
let state = { theme: 'light' };
const listeners = new Set();
tabsync('settings', {
get: () => state,
set: (next) => {
state = next;
listeners.forEach((fn) => fn());
},
subscribe: (fn) => (listeners.add(fn), () => listeners.delete(fn)),
});API
tabsync(name, store)
Keeps store in sync with the store of the same name in every other open tab. Returns a stop() function that closes the channel and unsubscribes.
| Parameter | Type | |
|---|---|---|
| name | string | Tabs with the same name share state. Use one name per store. |
| store.get | () => T | Returns the current value. |
| store.set | (value: T) => void | Called with the value from another tab. |
| store.subscribe | (listener) => unsubscribe | Calls listener after every change. Arguments passed to it are ignored. |
How it behaves:
- A local change is sent to the other tabs once. If the value didn't change, nothing is sent.
- A value received from another tab is passed to
set, and is not sent back. - On start, the tab asks the open tabs for the current state and adopts the first answer. If the user changes something before the answer arrives, their change wins.
- Tabs that started less than 100 ms ago don't answer, so a newcomer's defaults never overwrite a tab that's already open.
useTabSync(name, [state, setState]) from tab-sync-lite/react
Syncs a [state, setState] pair and returns it unchanged. Stops syncing on unmount.
Values are sent as JSON
Values are sent as JSON, not with the structured clone algorithm:
- Functions are left out, which is what you want for stores that hold actions (Zustand). Structured clone would throw.
Datebecomes a string,MapandSetbecome{}, andundefinedbecomesnull. Keep synced state to plain JSON data.
Browser support
Every browser with BroadcastChannel: Chrome, Edge, Firefox, and Safari 15.4+. Without it, tabsync does nothing and doesn't throw, so each tab simply keeps its own state.
FAQ
Does it persist state across reloads? No. It syncs open tabs. When the last tab closes, the state is gone. Pair it with your store's persistence (for example Zustand's persist middleware) if you need that.
What if two tabs change the same value at the same time? The last message to arrive wins in each tab. For settings, carts and login state that's fine. It is not a replacement for a server for data that must not be lost.
Is the data safe? BroadcastChannel only reaches pages of the same origin in the same browser profile. Values arrive as parsed JSON, so validate them in set if other code on your origin could post to the same channel.
Does it work in private windows or across browsers? Only between tabs of the same browser profile. A private window is its own profile.
Contributing
npm install
npm test # vitest + jsdom
npm run typecheck
npm run buildTo try the demo locally, run npm run build, serve the repo root (python3 -m http.server) and open /docs/.
License
MIT © Shivang Ramola
