React Router state synchronization across multiple tabs during token expiration
0 reputation · 17 Sept 2025, 06:50 UTC
0 reputation · 17 Sept 2025, 06:50 UTC
Since React state is volatile and local to the tab, a global logout triggered by an Axios interceptor does not automatically propagate to other open instances. Relying solely on 401 error handling can lead to a fragmented UI where the user appears authenticated in some views but unauthorized once the next data fetch fails.
What are the most efficient patterns for synchronizing session invalidation across concurrent browser contexts without introducing constant API polling? Can the Broadcast Channel API be integrated into a custom hook provider to ensure an immediate state reset when a token is revoked globally?
31275 reputation · 17 Sept 2025, 08:11 UTC
The most efficient pattern is a thin wrapper around the BroadcastChannel API that posts a LOGOUT message when any tab detects token expiry or an explicit logout. Other tabs listening on the same channel immediately clear their auth context and redirect via React Router. For browsers without BroadcastChannel (notably IE), fall back to a storage event on a dedicated localStorage key.
BroadcastChannel('auth-state') in a useEffect with an empty dependency array.logout function that clears local tokens, sets the user to null, posts { type: 'LOGOUT' } to the channel, and calls navigate('/login').LOGOUT, performs the same state reset and navigation. Return a cleanup function that removes the listener and closes the channel.auth-logout. When the key changes, trigger the same logout logic. The logout function should also set this key (e.g., localStorage.setItem('auth-logout', Date.now())) to activate the fallback.<Routes> so every route has access to the synchronized auth state.localStorage and BroadcastChannel, so each context behaves independently (which is usually the desired security posture)./login without a manual refresh.BroadcastChannel (e.g., via a feature flag or by testing in an older UA) and verify the storage fallback still works.One diagnostic detail needed: What is your minimum supported browser matrix? If Internet Explorer 11 must work, the storage fallback is mandatory; otherwise you can rely solely on BroadcastChannel and simplify the provider.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.