Your Session Is Shared. Your Store Is Not.
Auth lives in a cookie every tab can see. Redux lives in memory no tab can see. Here is the sign-in bug that asymmetry causes, and the BroadcastChannel wiring that closes it.
- React
- Architecture
A traveller has two tabs open. In the first they are signed out, browsing. In the second they sign in. They go back to the first tab, click into their account, and the app shows them a signed-out shell - or worse, calls an API with a token that no longer matches who they are and gets a 401 on a page that has no idea what to do with one.
Nobody wrote that bug. It falls out of an asymmetry that is easy to miss:
The session is shared. The store is not.
The cookie holding the access token is scoped to the origin, so every tab sees the same one, and the last tab to write it wins. The Redux store is per-page memory, so every tab has its own, and none of them are told when another one changes. One half of your auth state is global and one half is local, and the bug is simply the two drifting apart.
Why this gets worse, not better
The single-tab version of sign-in is the one everybody tests. The multi-tab version shows up in exactly the situations where it costs the most.
A parent managing their own loyalty account in one tab and their child's in another is the case that made this concrete for me. Both tabs share one cookie jar, so the server only ever has one session. Sign into the second tab and the first tab's in-memory store still insists it belongs to the first account - while the token it will actually send belongs to the second. The UI says one identity. The network says another. Every request from that tab is now acting on the wrong account with a straight face.
Session timeout has the same shape in reverse. Tab A sits idle and gets signed out. Tab B, which the user was actually reading, keeps rendering a full account view backed by a token that has already been revoked.
The fixes that do not work
Polling the cookie. You can read document.cookie on an interval and
diff it. This works, in the sense that it eventually notices. It is also a
timer that runs forever on every page to catch an event that happens twice a
session, and it still gives you a window - however short - where the tab is
confidently wrong.
The storage event. localStorage fires storage in other tabs when you
write to it, which is a real cross-tab signal and the pre-2020 answer. But you
are now encoding a transient message as persistent state, so you have to write
a value, read it, and clean it up, and you have to care what happens when two
tabs write in the same millisecond. You are using a filing cabinet as a
telephone.
Syncing the whole store. The idea arrives almost immediately once you have a channel: broadcast every action, let every tab apply it, and the stores stay identical. This is the one worth arguing about, because it sounds principled and it is a trap. Tabs are not meant to be identical. They are different positions in the app, with different scroll offsets, different open modals, different in-flight requests. Replicating every action means replicating transient UI state, racing two tabs' pending fetches against each other, and shipping every keystroke in a form to a tab that has no business seeing it.
What actually needs to cross a tab boundary is not the state. It is the two transitions that redefine who the user is.
BroadcastChannel
BroadcastChannel is the browser's answer to this and it is about as small as
an API gets. Name a channel, post to it, listen on it. Every other context on
the same origin - tabs, iframes, workers - receives the message. The posting
context does not receive its own message.
const channel = new BroadcastChannel('auth');
channel.postMessage({ type: 'SIGN_IN_SUCCESS' });
channel.addEventListener('message', (event) => {
console.log(event.data);
});That is the whole surface. Structured-cloneable payloads, no serialisation dance, no storage side effects. Everything interesting is in what you choose to send and what you do on receipt.
Only two actions are allowed to leave
The first decision is the one that keeps this from becoming a distributed state machine: an explicit allowlist, not a firehose.
// Actions permitted to cross a tab boundary. Deliberately short.
export const broadcastable = [SIGN_IN_SUCCESS, SIGN_OUT];Two entries. Signing in and signing out are the only events that invalidate another tab's entire view of the world, so they are the only ones that get to interrupt it. Everything else stays local, which is both correct and the reason this pattern stays debuggable - when a tab reloads unexpectedly, there are exactly two things it could have heard.
Outbound is then one line of saga:
export function* outbound() {
yield takeEvery(broadcastable, postToChannel);
}export const tabId = crypto.randomUUID();
export function postToChannel(action) {
if (action?.preventBroadcast) return;
channel.postMessage({ tabId, action });
}Inbound: a browser event as an action stream
Redux-Saga has exactly the right primitive for turning an event emitter into
something you can take from. eventChannel wraps the listener, and the
function it returns is the teardown - which matters, because an unremoved
listener on a channel you never close is a leak that survives navigation.
import { eventChannel } from 'redux-saga';
export function createAuthEventChannel(bc = channel) {
return eventChannel((emit) => {
const listener = (event) => {
const { tabId: senderId, action } = event.data;
// Ignore our own traffic: other same-origin contexts in *this* tab
// (iframes, for one) receive what we post.
if (senderId && action && senderId !== tabId) {
emit(action);
}
};
bc.addEventListener('message', listener);
return () => {
bc.removeEventListener('message', listener);
bc.close();
};
});
}The senderId !== tabId check deserves a note, because the spec already
promises the sender's own channel object will not receive the message. The
guard is not there for that. It is there because other contexts in the same
tab do receive it - a same-origin iframe running the same bundle is a
subscriber - and because an invariant you can read in the code beats one you
have to remember from a spec footnote.
Received messages become a plain action, so the rest of the app never touches the channel:
export function* inbound() {
const bc = yield call(createAuthEventChannel);
yield takeEvery(bc, function* (action) {
yield put({ type: BC_MESSAGE, originalAction: action });
});
}The echo
Here is the part that bites, and it bites immediately.
A received action has to be dispatched locally to do anything. The moment you dispatch it, the outbound watcher sees a whitelisted action and broadcasts it. The other tab receives it, dispatches it, broadcasts it back. Two tabs will wedge each other in a loop that neither one started, and it will look like a mystery until you notice the action type in the log is one you already handled.
The fix is a single flag that marks an action as having already travelled:
yield put({ ...originalAction, preventBroadcast: true });postToChannel returns early on it. The action still flows through reducers
and sagas exactly as a local one would - it just cannot make another trip. One
boolean, and the re-entrancy is gone.
This is the general shape of every message-passing bug I have had to unpick: the system is fine, and then something it emitted comes back in through its own input.
Reloading on purpose
The reconciliation step is where I expected to write the most code and ended up writing the least.
export function* reconcile() {
while (true) {
const { originalAction } = yield take(BC_MESSAGE);
if (originalAction.type === SIGN_IN_SUCCESS) {
const route = yield select(selectCurrentRoute());
if (PRESERVE_ROUTES.some((r) => route.includes(r))) {
// Mid-flow: adopt the new identity in place rather than
// destroying work the user cannot get back.
yield put({ ...originalAction, preventBroadcast: true, getAnonToken: false });
} else {
window.location.reload();
}
continue;
}
if (originalAction.type === SIGN_OUT) {
yield put({ ...originalAction, preventBroadcast: true, getAnonToken: false });
window.location.reload();
}
}
}window.location.reload() in a single-page app reads like giving up. I would
defend it as the opposite.
Consider what is actually stale in a tab the moment the identity behind it changes: the profile, the cart, every price that depended on loyalty status, the navigation, any cached query keyed by user, and every request currently in flight carrying the old token. A rehydration path that correctly invalidates all of that is not a small function - it is a parallel implementation of app startup, maintained forever, and wrong in a new way every time someone adds a slice. The reload is the startup path, already written and already tested on every cold load. It costs a second, it happens twice a session, and the user's mental model of "I signed in, the page updated" survives it intact.
The exception is the interesting part. On a route holding work the user cannot reconstruct - a rebooking in progress, a form six steps deep - a reload is no longer the cheap option, it is data loss. There the tab adopts the new identity in place and accepts that some derived state will be briefly imperfect. That is the right trade exactly once, on routes you can name and count.
getAnonToken: false is the small companion to this. The tab that originated
the sign-out already handled the token lifecycle; a receiving tab that also
goes off to fetch a fresh anonymous token is racing its sibling for no reason.
The receiver's job is to adopt what happened, not to re-enact it.
What I would tell you before you build this
Name the two transitions first. Not the state you want to share - the events that make a tab's whole view obsolete. For auth there are two. If your list has eight entries on it, you are building store replication and you should stop.
Expect the echo. Any action that can be received and re-dispatched needs a flag saying it has already travelled. Design it in; do not wait to find it.
Close the channel. eventChannel's return value is the teardown, and
bc.close() belongs in it next to removeEventListener.
Know what it does not cover. BroadcastChannel is same-origin only, so
two browser profiles, or a normal and an incognito window, remain two
independent sessions - which is correct, and also means this is not a substitute
for the server treating the token as the source of truth. Support is universal
in current browsers but was not always; if you need an old Safari, storage
is still the fallback, with the filing-cabinet caveats intact.
The pattern underneath all of this is worth separating from the API. Two surfaces disagreed because one was shared and one was not. The fix was not to make them both shared. It was to notice which transitions made the private half worthless, and to say those out loud.
Where this came from. This is the cross-tab sign-in work on united.com. The reported bug looked small - sign in on one tab, and the other tab still renders a signed-out shell. What made it worth fixing properly was the version underneath: two tabs sharing one cookie jar while holding two separate in-memory stores, so the tab you were not looking at would keep acting on an identity that had already been replaced. Travellers managing more than one account - a parent and a child, most commonly - hit it hardest, because there the wrong identity is not a broken page, it is the wrong account. The fix in production is the allowlist above: two actions cross a tab boundary, and everything else stays exactly where it was.