@lorb/tab-sync
v0.1.0
Published
Cross-tab state sync via BroadcastChannel. Login in one tab, every tab knows
Maintainers
Readme
@lorb/tab-sync
Cross-tab state sync via BroadcastChannel. Login in one tab, every tab knows.
Install
npm install @lorb/tab-syncUsage
import { init, sync, on } from '@lorb/tab-sync';
const cleanup = init();
// Sync any value across tabs
sync('cart', { items: 3 });
on('cart', (value) => updateCartBadge(value.items));Auth sync -- the most common case:
import { init, syncAuth, onAuthChange } from '@lorb/tab-sync';
init();
// Tab A: user logs in
syncAuth(token);
// Tab B, C, D: instant update
onAuthChange((token) => {
if (!token) window.location.href = '/login';
});Theme sync:
import { init, syncTheme, onThemeChange } from '@lorb/tab-sync';
init();
syncTheme('dark');
onThemeChange((mode) => {
document.documentElement.dataset.theme = mode;
});Why
Users expect cross-tab consistency. BroadcastChannel does this natively, but the raw API is tedious. tab-sync adds typed key-value sync, built-in auth/theme helpers, and automatic leader election in a few lines.
API
init()-- start syncing, returns cleanup functionsync(key, value)-- broadcast a value to all tabson(key, callback)-- listen for changes from other tabsget(key)-- get the last synced valuesyncAuth(token)/onAuthChange(cb)-- auth shorthandsyncTheme(mode)/onThemeChange(cb)-- theme shorthandtabCount()-- number of active tabsisLeader()-- whether this tab is the leaderonLeaderChange(cb)-- leader election eventsdestroy()-- teardown
SSR-safe. No-op when BroadcastChannel is unavailable.
License
MIT -- Lorb.studio
