Skip to content

Commit deeb40d

Browse files
committed
Apparently, using singletons on the server leads to data leaks
1 parent 06821c1 commit deeb40d

1 file changed

Lines changed: 17 additions & 5 deletions

File tree

src/integrations/tanstack-query/root-provider.tsx

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
11
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
22

3-
// Singleton queryClient to ensure the same instance is used everywhere
4-
let queryClientSingleton: QueryClient | null = null;
3+
// Client-side singleton to ensure the same instance is used across the app
4+
let clientQueryClient: QueryClient | null = null;
5+
6+
function makeQueryClient() {
7+
return new QueryClient();
8+
}
59

610
export function getContext() {
7-
if (!queryClientSingleton) {
8-
queryClientSingleton = new QueryClient();
11+
// Server: always create a new QueryClient per request to avoid data leaks
12+
if (typeof window === "undefined") {
13+
return {
14+
queryClient: makeQueryClient(),
15+
};
16+
}
17+
18+
// Client: use singleton to preserve cache across navigations
19+
if (!clientQueryClient) {
20+
clientQueryClient = makeQueryClient();
921
}
1022
return {
11-
queryClient: queryClientSingleton,
23+
queryClient: clientQueryClient,
1224
};
1325
}
1426

0 commit comments

Comments
 (0)