Skip to content

[5 BOUNTY] [TypeScript] Add single-flight token refresh handling - #9

Open
alKanz17 wants to merge 1 commit into
shaiananvari8:mainfrom
alKanz17:fix/single-flight-token-refresh
Open

[5 BOUNTY] [TypeScript] Add single-flight token refresh handling#9
alKanz17 wants to merge 1 commit into
shaiananvari8:mainfrom
alKanz17:fix/single-flight-token-refresh

Conversation

@alKanz17

Copy link
Copy Markdown

What this does

Replaces the racy token refresh logic with a single-flight coordination pattern, eliminating the multi-tab refresh race.

How it works

  • singleFlightRefresh() — stores the in-flight HTTP call in a module-level promise. All concurrent callers (same tab or cross-tab) share the same promise, guaranteeing exactly one /auth/refresh request.
  • BroadcastChannel API — after a successful refresh, the winning tab broadcasts the new tokens via a BroadcastChannel. Sibling tabs receive the message and update their local state without making redundant refresh calls. The TOKEN_UPDATE_EVENT carries the full AuthTokens object.
  • listenForTokenUpdates() — registers a BroadcastChannel message handler that validates and applies incoming tokens, then reschedules the local refresh timer.
  • Graceful fallback — BroadcastChannel API availability is checked lazily. When unavailable (Node, older browsers), the single-flight still works within the same tab and cross-tab coordination is silently skipped.
  • Cleanup — refreshPromise is nulled in the finally block, and stale tokens are cleared on failure.

Closes #1

- Implemented singleFlightRefresh() that deduplicates concurrent refresh
  calls via a shared promise — only one HTTP /auth/refresh is in-flight
  regardless of how many callers trigger a refresh simultaneously
- Added BroadcastChannel-based cross-tab coordination: when one tab
  refreshes the token, it broadcasts the new tokens to sibling tabs so
  they stay in sync without making their own refresh calls
- Added listenForTokenUpdates() which listens for broadcast messages
  and updates local state + localStorage + reschedules refresh timer
- Added broadcastTokenUpdate() to propagate new tokens to other tabs
- Replaced inline refresh logic in refreshTokens() with singleFlightRefresh()

Closes jackjin1997#1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[$35 BOUNTY] [TypeScript] Add single-flight token refresh handling

1 participant