fix(broadcast-client): handle unhandled postMessage rejections
Summary
Fixes #10543
broadcastQueryClient calls channel.postMessage() three times (on updated, removed, added) without .catch()-ing the returned promise. When query data contains a non-cloneable value (ReadableStream, Response, File, functions, Vue/MobX reactive proxies, etc.), the rejection becomes an unhandled DataCloneError with a stack pointing into node_modules โ effectively unactionable in Sentry/Datadog.
Changes
- Wrap all
channel.postMessage()calls in asafePost()helper that catches rejections - Add optional
onBroadcastErrorcallback toBroadcastQueryClientOptionsso consumers can route errors to their own error tracker with the offendingqueryHash - Fall back to
console.warnin development whenonBroadcastErroris not provided - Silent in production (no unhandled rejection, no console noise)
Usage
broadcastQueryClient({
queryClient,
broadcastChannel: 'my-app',
onBroadcastError: (error, message) => {
Sentry.captureException(error, {
extra: { queryHash: message.queryHash, type: message.type },
})
},
})
Test plan
- [x]
onBroadcastErroris called with the error and message whenpostMessagerejects - [x]
console.warnis emitted in development when noonBroadcastErroris provided - [x] No warning in production when
postMessagefails - [x] Existing tests still pass
- [x] ESLint passes
๐ค Generated with Claude Code
Summary by CodeRabbit
-
Bug Fixes
- Prevented unhandled rejections when cross-tab broadcast fails due to non-serializable data; failures are now caught to avoid noisy errors.
-
New Features
- Added an optional broadcast-error callback so apps can handle broadcast failures explicitly; when omitted, development builds emit console warnings.
- Reduced broadcast payload size by omitting state for removed items.
-
Documentation
- Added guidance and examples for handling broadcast errors.
-
Tests
- Expanded tests to cover broadcast error handling and warning behavior.
No actionable comments were generated in the recent review. ๐
โน๏ธ Recent review info
โ๏ธ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 2b48a45c-71ca-4d47-b171-5934da15836c
๐ฅ Commits
Reviewing files that changed from the base of the PR and between b32ff8ea9bcbd6627c8b44a758857f3c1586b513 and 52d17622dbcd1c7f89bd274ce8a994b496b9a4fb.
๐ Files selected for processing (1)
packages/query-broadcast-client-experimental/src/__tests__/index.test.ts
๐ Walkthrough
Walkthrough
broadcastQueryClient wraps outbound BroadcastChannel.postMessage in safePost and accepts an optional onBroadcastError(error, event); failures invoke the callback (handling throws/rejections) or emit a development-only console.warn. updated/added include state; removed omits state. Tests, docs, and a changeset were added.
Changes
Broadcast error handling and recovery
| Layer / File(s) | Summary |
|---|---|
Options interface and callback setup packages/query-broadcast-client-experimental/src/index.ts |
Adds exported BroadcastErrorEvent and an optional `onBroadcastError?: (error: unknown, event: BroadcastErrorEvent) => void |
Safe post helper with error handling packages/query-broadcast-client-experimental/src/index.ts |
Introduces safePost wrapping channel.postMessage to catch rejections and call onBroadcastError(error, event) when provided; tolerates sync throws and promise rejections and falls back to a development-only console.warn. |
Integrate safePost into broadcast paths packages/query-broadcast-client-experimental/src/index.ts |
Replaces direct postMessage calls for updated, removed, and added with safePost; updated/added payloads include state, removed omits state. |
Test mock setup and error handling scenarios packages/query-broadcast-client-experimental/src/__tests__/index.test.ts |
Adds controllable postMessage/close spies, resets them between tests, and adds a postMessage error handling suite forcing rejections to verify onBroadcastError invocation, no unhandledRejection when handler throws/rejects, and environment-dependent console.warn behavior. |
Docs: API and handling section docs/framework/react/plugins/broadcastQueryClient.md |
Documents onBroadcastError and BroadcastErrorEvent; adds a "Handling broadcast errors" section with explanation and an example (Sentry integration). |
Release notes .changeset/fix-broadcast-client-unhandled-rejection.md |
Patch changeset documenting the fix for unhandled DataCloneError rejections, the new optional onBroadcastError callback, and the development fallback to console.warn. |
sequenceDiagram
participant BroadcastQueryClient
participant BroadcastChannel
participant onBroadcastError
participant Console
BroadcastQueryClient->>BroadcastChannel: safePost(message) -> postMessage(message)
BroadcastChannel--xBroadcastQueryClient: rejection (DataCloneError)
BroadcastQueryClient->>onBroadcastError: onBroadcastError(error, event)
onBroadcastError-->>BroadcastQueryClient: may throw / reject
BroadcastQueryClient->>Console: console.warn(type, queryHash, error) (dev-only fallback)
๐ฏ 3 (Moderate) | โฑ๏ธ ~20 minutes
- TkDodo
๐ฐ I hopped through code with care and cheer,
When messages failed, I caught them near.
Errors routed, no noisy fright,
Callbacks listen, devs see light.
Broadcasts hum softly through the night.
๐ฅ Pre-merge checks | โ 4 | โ 1
โ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | โ ๏ธ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
โ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | โ Passed | The title accurately and concisely summarizes the main change: fixing unhandled postMessage rejections in the broadcast client. |
| Description check | โ Passed | The description covers the motivation (issue #10543), key changes (safePost helper, onBroadcastError callback), usage example, and confirms test coverage and linting checks. |
| Linked Issues check | โ Passed | The implementation comprehensively addresses #10543: wraps postMessage calls in safePost, provides optional onBroadcastError callback with BroadcastErrorEvent, uses console.warn in dev when no callback, and maintains silence in production. |
| Out of Scope Changes check | โ Passed | All changes directly support the primary objective of handling postMessage rejections; the state inclusion fix in 'added' broadcasts is a related bug fix identified during implementation. |
โ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.
โจ Finishing Touches
๐งช Generate unit tests (beta)
- [ ] Create PR with unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Fixed in the latest commit: wrapped both unhandledRejection listener tests in try/finally so process.off() is always called even if an assertion throws.
Update summary
After reviewing other PRs addressing the same issue (#10569, #10770, #10697) and the CodeRabbit feedback, I've made additional improvements beyond the initial unhandled-rejection fix. Here's a full summary of what's in the branch now.
Changes from the original PR
Types
- Exported
BroadcastErrorEventinterface (withqueryKey: QueryKey) so consumers can import and reference the type directly:import type { BroadcastErrorEvent } from '@tanstack/query-broadcast-client-experimental' - Replaced the flat
BroadcastMessageinterface with a discriminated union โstateis now only present onupdatedandadded(notremoved), which matches the actual wire protocol onBroadcastErrornow receivesBroadcastErrorEvent(no internalstatefield) rather than the raw message objectonBroadcastErrorreturn type isvoid | Promise<void>to explicitly support async callbacks
Error handling in safePost
| Case | Behaviour |
|---|---|
postMessage rejects |
onBroadcastError called with error + event; or dev console.warn if no callback |
onBroadcastError throws synchronously |
Caught by try/catch; dev console.warn with callback error |
onBroadcastError returns a rejecting Promise |
Caught by result?.catch(); dev console.warn with callback error |
| Production, no callback | Silent โ no unhandled rejection, no console noise |
Warning messages
Two distinct messages to make debugging easier:
- Broadcast failure (no callback):
[broadcastQueryClient] Failed to broadcast "X" event for query Y. The query value could not be structured-cloned; cross-tab sync for this query was skipped. - Callback itself failed:
[broadcastQueryClient] onBroadcastError threw while handling "X" for query Y.
Bug fix: state missing from 'added' broadcasts
The receiver's onmessage handler reads state for added events (query.setState(state) / queryCache.build(..., state)), but the sender was omitting it โ causing receiving tabs to apply undefined state. Fixed by including state in the outbound added message and updating the discriminated union accordingly.
Other
- Replaced
queryClient.getQueryCache().subscribe()withqueryCache.subscribe()(variable already in scope) - Added JSDoc to all
BroadcastQueryClientOptionsfields - Added "Handling broadcast errors" section to the docs with a Sentry example
CodeRabbit review responses
| Comment | Resolution |
|---|---|
onBroadcastError throwing causes a new unhandled rejection |
Wrapped callback in try/catch; added test asserting zero unhandledRejection events when callback throws |
Async onBroadcastError rejecting causes unhandled rejection |
Extended type to void | Promise<void>; added result?.catch() guard; added test for async rejection path |
'added' broadcasts omit state, breaking receiver contract |
Added state to the added discriminated union variant and to the safePost call site; confirmed with existing tests |
Test coverage (9 tests)
- subscribe / unsubscribe (existing)
onBroadcastErrorcalled whenpostMessagerejects- No unhandled rejection when callback throws synchronously
- Dev
console.warnemitted when callback throws (asserts message contains"onBroadcastError threw while handling") - No unhandled rejection when async callback rejects
- Dev
console.warnemitted when async callback rejects - Dev
console.warnemitted when no callback provided (asserts"cross-tab sync for this query was skipped") - No
console.warnin production
@coderabbitai resume
Reviews resumed.โ
Actions performed
Addressed in the latest commit (52d17622d).
All four tests that call vi.spyOn(console, 'warn') now wrap their assertions in try/finally so mockRestore() is guaranteed to run even if an assertion fails โ preventing the spy from leaking into subsequent tests.
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
// ...test body and assertions...
} finally {
warnSpy.mockRestore()
}
Applied to:
should warn in dev when onBroadcastError itself throwsshould warn in dev when async onBroadcastError rejectsshould warn in dev when postMessage fails and onBroadcastError is not providedshould not warn in production when postMessage fails