Open History to see the last commit
1import { BroadcastChannel } from 'broadcast-channel'
2import type { BroadcastChannelOptions } from 'broadcast-channel'
3import type { QueryClient, QueryKey } from '@tanstack/query-core'
4β
5/**
6 * Metadata describing a broadcast that failed to be delivered to other tabs.
7 * Passed to {@link BroadcastQueryClientOptions.onBroadcastError} so callers can
8 * correlate failures with the originating query.
9 */
10export interface BroadcastErrorEvent {
11 /** The kind of cache event that was being broadcast. */
12 type: 'updated' | 'removed' | 'added'
13 /** The hash of the query the broadcast was about. */
14 queryHash: string
15 /** The key of the query the broadcast was about. */
16 queryKey: QueryKey
17}
18β
19type BroadcastMessage =
20 | { type: 'updated'; queryHash: string; queryKey: QueryKey; state: unknown }
21 | { type: 'removed'; queryHash: string; queryKey: QueryKey }
22 | { type: 'added'; queryHash: string; queryKey: QueryKey; state: unknown }
23β
24interface BroadcastQueryClientOptions {
25 /** The QueryClient to sync. */
26 queryClient: QueryClient
27 /**
28 * Unique channel name used to communicate between tabs and windows.
29 *
30 * @default 'tanstack-query'
31 */
32 broadcastChannel?: string
33 /** Options forwarded to the underlying `BroadcastChannel`. */
34 options?: BroadcastChannelOptions
35 /**
36 * Called when a query event fails to broadcast to other tabs β most commonly
37 * because the query's `state.data`, `state.error`, or `queryKey` contains a
38 * value the structured-clone algorithm cannot serialize (e.g.
39 * `ReadableStream`, `File`, functions, Vue `reactive` proxies).
40 *
41 * Provide this to route failures to an error tracker. If omitted, a
42 * `console.warn` is emitted in development so failures are never silent.
43 *
44 * May return a `Promise`; any rejection is caught internally so it cannot
45 * cause a secondary unhandled rejection.
46 */
47 onBroadcastError?: (
48 error: unknown,
49 event: BroadcastErrorEvent,
50 ) => void | Promise<void>
51}
52β
53/**
54 * Syncs a client's query cache with the caches of other tabs and windows
55 * through a `BroadcastChannel`: added queries, successful updates, and removals
56 * of queries that have observers are broadcast, and those received from other
57 * tabs are applied.
58 *
59 * @param options - The `queryClient` to sync, the `broadcastChannel` name, the
60 * channel `options`, and the `onBroadcastError` callback.
61 * @returns A function that stops syncing and closes the channel.
62 */
63export function broadcastQueryClient({
64 queryClient,
65 broadcastChannel = 'tanstack-query',
66 options,
67 onBroadcastError,
68}: BroadcastQueryClientOptions): () => void {
69 let transaction = false
70 const tx = (cb: () => void) => {
71 transaction = true
72 try {
73 cb()
74 } finally {
75 // Guard against `cb` throwing (e.g. `query.setState`/`queryCache.build`
76 // triggering a listener that throws while applying an incoming
77 // cross-tab message). Without this, `transaction` would stay `true`
78 // forever, silently disabling this tab's own broadcasts to other tabs
79 // for the rest of the session.
80 transaction = false
81 }
82 }
83β
84 const channel = new BroadcastChannel(broadcastChannel, {
85 webWorkerSupport: false,
86 ...options,
87 })
88β
89 const queryCache = queryClient.getQueryCache()
90β
91 const safePost = (message: BroadcastMessage): void => {
92 channel.postMessage(message).catch((error: unknown) => {
93 const event: BroadcastErrorEvent = {
94 type: message.type,
95 queryHash: message.queryHash,
96 queryKey: message.queryKey,
97 }
98β
99 if (onBroadcastError) {
100 const warnCallbackError = (callbackError: unknown) => {
101 if (process.env.NODE_ENV !== 'production') {
102 console.warn(
103 `[broadcastQueryClient] onBroadcastError threw while handling "${event.type}" for query ${event.queryHash}.`,
104 callbackError,
105 )
106 }
107 }
108 let result: void | Promise<void>
109 try {
110 result = onBroadcastError(error, event)
111 } catch (callbackError) {
112 warnCallbackError(callbackError)
113 return
114 }
115 result?.catch(warnCallbackError)
116 } else if (process.env.NODE_ENV !== 'production') {
117 console.warn(
118 `[broadcastQueryClient] Failed to broadcast "${event.type}" event for query ${event.queryHash}. ` +
119 'The query value could not be structured-cloned; cross-tab sync for this query was skipped.',
120 error,
121 )
122 }
123 })
124 }
125β
126 const unsubscribe = queryCache.subscribe((queryEvent) => {
127 if (transaction) {
128 return
129 }
130β
131 const {
132 query: { queryHash, queryKey, state, observers },
133 } = queryEvent
134β
135 if (queryEvent.type === 'updated' && queryEvent.action.type === 'success') {
136 safePost({
137 type: 'updated',
138 queryHash,
139 queryKey,
140 state,
141 })
142 }
143β
144 if (queryEvent.type === 'removed' && observers.length > 0) {
145 safePost({
146 type: 'removed',
147 queryHash,
148 queryKey,
149 })
150 }
151β
152 if (queryEvent.type === 'added') {
153 safePost({
154 type: 'added',
155 queryHash,
156 queryKey,
157 state,
158 })
159 }
160 })
161β
162 channel.onmessage = (action) => {
163 if (!action?.type) {
164 return
165 }
166β
167 tx(() => {
168 const { type, queryHash, queryKey, state } = action
169β
170 const query = queryCache.get(queryHash)
171β
172 if (type === 'updated') {
173 if (query) {
174 query.setState(state)
175 return
176 }
177β
178 queryCache.build(
179 queryClient,
180 {
181 queryKey,
182 queryHash,
183 },
184 state,
185 )
186 } else if (type === 'removed') {
187 if (query) {
188 queryCache.remove(query)
189 }
190 } else if (type === 'added') {
191 if (query) {
192 if (query.state.data === undefined) {
193 query.setState(state)
194 }
195 return
196 }
197 queryCache.build(
198 queryClient,
199 {
200 queryKey,
201 queryHash,
202 },
203 state,
204 )
205 }
206 })
207 }
208 return () => {
209 unsubscribe()
210 channel.close()
211 }
212}