Open History to see the last commit
1import { isPlatformBrowser, isPlatformServer } from '@angular/common'
2import {
3 DOCUMENT,
4 DestroyRef,
5 InjectionToken,
6 PLATFORM_ID,
7 TransferState,
8 inject,
9 makeEnvironmentProviders,
10 makeStateKey,
11 provideEnvironmentInitializer,
12} from '@angular/core'
13import { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'
14import { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'
15import { injectQueryZone } from './utils/inject-query-zone'
16import type { DehydratedState } from '@tanstack/query-core'
17import type { EnvironmentProviders } from '@angular/core'
18​
19const INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {
20 providedIn: 'root',
21 factory: () => true,
22})
23​
24/**
25 * Mounts the injected client, configures server defaults, and connects TransferState hydration.
26 */
27function configureQueryClient() {
28 const queryClient = inject(QueryClient)
29 const destroyRef = inject(DestroyRef)
30 const platformId = inject(PLATFORM_ID)
31​
32 if (isPlatformServer(platformId)) {
33 // DOM emulation can fool core's runtime detection. Apply server defaults to
34 // this client without changing other clients or global scheduling providers.
35 const defaults = queryClient.getDefaultOptions()
36 queryClient.setDefaultOptions({
37 ...defaults,
38 queries: { gcTime: Infinity, retry: false, ...defaults.queries },
39 mutations: { gcTime: Infinity, ...defaults.mutations },
40 })
41 }
42 const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)
43 const hydrationStateKey = inject(
44 INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
45 )
46​
47 if (inject(DOCUMENT, { optional: true })) {
48 const transferState = inject(TransferState)
49​
50 if (shouldHydrate && isPlatformServer(platformId)) {
51 transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))
52 } else if (shouldHydrate && isPlatformBrowser(platformId)) {
53 const dehydratedState = transferState.get(hydrationStateKey, null)
54 if (dehydratedState) {
55 hydrate(queryClient, dehydratedState)
56 transferState.remove(hydrationStateKey)
57 }
58 }
59 }
60​
61 queryClient.mount()
62 destroyRef.onDestroy(() => queryClient.unmount())
63}
64​
65/**
66 * Provides a `QueryClient` and optional TanStack Query features.
67 * The factory runs once per injector in Angular's injection context, so it can
68 * call `inject()` and each SSR request can receive an independent cache.
69 * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.
70 * @param features - Optional features to configure additional Query functionality.
71 * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
72 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
73 * @see https://tanstack.com/query/v5/docs/framework/angular/devtools
74 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr
75 * @example
76 * ```ts
77 * import {
78 * provideTanStackQuery,
79 * QueryClient,
80 * } from '@tanstack/angular-query'
81 *
82 * bootstrapApplication(AppComponent, {
83 * providers: [provideTanStackQuery(() => new QueryClient())],
84 * })
85 * ```
86 *
87 * You can also enable optional developer tools by adding `withDevtools`. By
88 * default the tools will then be loaded when your app is in development mode.
89 *
90 * ```ts
91 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
92 * import { withDevtools } from '@tanstack/angular-query-devtools'
93 *
94 * bootstrapApplication(AppComponent, {
95 * providers: [
96 * provideTanStackQuery(() => new QueryClient(), withDevtools()),
97 * ],
98 * })
99 * ```
100 */
101export function provideTanStackQuery(
102 queryClientFactory: () => QueryClient,
103 ...features: ReadonlyArray<QueryFeature>
104): EnvironmentProviders {
105 return makeEnvironmentProviders([
106 {
107 provide: QueryClient,
108 useFactory: () => injectQueryZone()(queryClientFactory),
109 },
110 ...features.map(getQueryFeatureProviders),
111 provideEnvironmentInitializer(configureQueryClient),
112 ])
113}
114​
115const queryFeatureBrand: unique symbol = Symbol('QueryFeature')
116​
117/**
118 * Opaque configuration returned by Query feature functions such as `withHydrationKey`.
119 * Pass features to `provideTanStackQuery`; applications do not construct them directly.
120 */
121export interface QueryFeature {
122 /** @internal */
123 readonly [queryFeatureBrand]: true
124}
125​
126interface InternalQueryFeature extends QueryFeature {
127 readonly ɵproviders: EnvironmentProviders
128}
129​
130/**
131 * Creates a feature shared by Angular Query integration packages.
132 * @internal
133 * @param providers - Providers owned by this Query feature.
134 * @returns An opaque feature that installs the supplied environment providers.
135 */
136export function queryFeature(providers: EnvironmentProviders): QueryFeature {
137 const feature: InternalQueryFeature = {
138 [queryFeatureBrand]: true,
139 ɵproviders: providers,
140 }
141​
142 return feature
143}
144​
145/**
146 * Gets the environment providers owned by an opaque Query feature.
147 * @internal
148 * @param feature - The feature to unwrap.
149 * @returns The environment providers to install.
150 */
151export function getQueryFeatureProviders(
152 feature: QueryFeature,
153): EnvironmentProviders {
154 return (feature as InternalQueryFeature).ɵproviders
155}
156​
157/**
158 * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /
159 * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
160 * so each has its own key. The default key applies when you do not add this feature.
161 *
162 * ```ts
163 * providers: [
164 * provideTanStackQuery(
165 * () => new QueryClient(),
166 * withHydrationKey('my-secondary-query-cache'),
167 * ),
168 * ]
169 * ```
170 * @param key - A unique string for this client's `TransferState` entry.
171 * @returns A feature that stores this client's cache under the supplied key.
172 */
173export function withHydrationKey(key: string): QueryFeature {
174 return queryFeature(
175 makeEnvironmentProviders([
176 {
177 provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
178 useValue: makeStateKey<DehydratedState>(key),
179 },
180 ]),
181 )
182}
183​
184/**
185 * Disables `TransferState` hydration and dehydration for the current environment injector.
186 * @returns A feature that prevents automatic cache transfer for this injector.
187 */
188export function withNoQueryHydration(): QueryFeature {
189 return queryFeature(
190 makeEnvironmentProviders([
191 {
192 provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,
193 useValue: false,
194 },
195 ]),
196 )
197}