Cross-Tab Sync
Keep auth state consistent across browser tabs.
If a user is logged in across three tabs and they log out in tab A, you almost always want tabs B and C to react. Nest Auth ships a small CrossTabSync helper that broadcasts auth events between tabs so each <AuthProvider> reacts.
How it works
Under the hood:
BroadcastChannelif available (Chrome, Firefox, Safari ≥ 15.4, modern Edge).- Falls back to
localStoragestorageevents for older browsers.
Either way, all tabs in the same origin see the same broadcast.
Setup
Create a sync instance and connect it to your client:
API
| Method | Purpose |
|---|---|
subscribe(handler) | Listen for events from other tabs. Returns unsubscribe |
broadcast(type) | Generic broadcast |
broadcastLogout() | Shorthand for broadcast('logout') |
broadcastLogin() | Shorthand for broadcast('login') |
broadcastRefresh() | Shorthand for broadcast('refresh') |
destroy() | Tear down the channel / storage listener |
Event types
timestamp lets you ignore stale events if you receive multiple in quick succession.
Watch out
- Don't broadcast on every refresh. Auto-refresh fires often. Pick a less chatty signal — broadcast on login/logout only.
- Loop avoidance. When tab A receives a
logoutevent from tab B, don't broadcast anotherlogout— just react locally. Otherwise you cause a fanout storm. - Cookie mode is partly self-syncing. When the server clears the auth cookies on logout, all tabs see them disappear on their next request. Cross-tab sync is still useful for immediate UI updates rather than waiting for the next request.
Test
The simplest manual test: open two tabs, log in on both, log out in tab A. Tab B should redirect to /login within a render cycle.