Capítulo 50 de 80

Chapter 50: broadcastQueryClient (Experimental)

Core Idea

Syncs a QueryClient's state across same-origin browser tabs/windows via the BroadcastChannel API — experimental (breaking changes possible in minor/patch releases), and silently skips syncing individual queries whose data isn't structured-cloneable rather than failing the whole broadcast.

Key Concepts

  • Package: separate, @tanstack/query-broadcast-client-experimental.
  • Setup: broadcastQueryClient({ queryClient, broadcastChannel })broadcastChannel is the channel name tabs coordinate on (default 'tanstack-query'); use a unique name per app to avoid cross-app collisions on the same origin.
  • Structured-clone limitation: BroadcastChannel.postMessage (the underlying transport) can't serialize everything — ReadableStream (e.g. from Response.body, streaming/AI SDK responses), File, functions, or framework reactivity proxies (Vue reactive) all fail to clone. When that happens, cross-tab sync is skipped for that one query only; the rest of the cache keeps broadcasting normally — it's a per-query failure, not a global one.
  • onBroadcastError: by default, a clone failure only logs a console.warn in development (never fully silent) — provide this callback to route failures to real error tracking instead, receiving both the raw error and a BroadcastErrorEvent (type, queryHash, queryKey) for context.

Code Examples

broadcastQueryClient({
  queryClient,
  broadcastChannel: 'my-app',
  onBroadcastError: (error, event) => {
    Sentry.captureException(error, { extra: { queryHash: event.queryHash } })
  },
})
  • What it demonstrates: routing a per-query broadcast failure to external error tracking instead of relying on the default dev-only console warning.

Key Takeaways

  1. Pin to a patch version if relying on this in production — it's explicitly experimental and can break in minor/patch releases.
  2. Audit any query whose data includes streams, files, functions, or reactive proxies — those specific queries silently won't sync across tabs unless handled.
  3. Wire onBroadcastError in production apps rather than relying on the dev-only console warning to surface clone failures.

Connects To

  • QueryClient: the instance being synced across tabs.
  • persistQueryClient: a related but distinct concern (storage persistence vs. cross-tab sync) — the two can be combined.