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 { EnvironmentProviders } from '@angular/core'
17import type { DehydratedState } from '@tanstack/query-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 * Sets up providers necessary to enable TanStack Query functionality for Angular applications. Provides a
67 * `QueryClient` and optional TanStack Query features. The factory runs once per injector in Angular's
68 * injection context, so it can 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 * @example
87 * The same, in an `NgModule`-based application:
88 * ```ts
89 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
90 *
91 * @NgModule({
92 * declarations: [AppComponent],
93 * imports: [BrowserModule],
94 * providers: [provideTanStackQuery(() => new QueryClient())],
95 * bootstrap: [AppComponent],
96 * })
97 * export class AppModule {}
98 * ```
99 * @example
100 * Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when
101 * your app is in development mode:
102 * ```ts
103 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
104 * import { withDevtools } from '@tanstack/angular-query-devtools'
105 *
106 * bootstrapApplication(AppComponent, {
107 * providers: [
108 * provideTanStackQuery(() => new QueryClient(), withDevtools()),
109 * ],
110 * })
111 * ```
112 * @example
113 * Resolving the `QueryClient` from an `InjectionToken` — an advanced optimization that lets TanStack Query
114 * be absent from the main application bundle, useful for including it on lazy-loaded routes only while
115 * still sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to
116 * provide the `QueryClient` in the main application config, as in the examples above:
117 * ```ts
118 * export const MY_QUERY_CLIENT = new InjectionToken('', {
119 * factory: () => new QueryClient(),
120 * })
121 *
122 * // In a lazy loaded route's providers array:
123 * providers: [provideTanStackQuery(() => inject(MY_QUERY_CLIENT))]
124 * ```
125 */
126export function provideTanStackQuery(
127 queryClientFactory: () => QueryClient,
128 ...features: ReadonlyArray<QueryFeature>
129): EnvironmentProviders {
130 return makeEnvironmentProviders([
131 {
132 provide: QueryClient,
133 useFactory: () => injectQueryZone()(queryClientFactory),
134 },
135 ...features.map(getQueryFeatureProviders),
136 provideEnvironmentInitializer(configureQueryClient),
137 ])
138}
139​
140const queryFeatureBrand: unique symbol = Symbol('QueryFeature')
141​
142/**
143 * Opaque configuration returned by Query feature functions such as `withHydrationKey`.
144 * Pass features to `provideTanStackQuery`; applications do not construct them directly.
145 */
146export interface QueryFeature {
147 /** @internal */
148 readonly [queryFeatureBrand]: true
149}
150​
151interface InternalQueryFeature extends QueryFeature {
152 readonly ɵproviders: EnvironmentProviders
153}
154​
155/**
156 * Creates a feature shared by Angular Query integration packages.
157 * @internal
158 * @param providers - Providers owned by this Query feature.
159 * @returns An opaque feature that installs the supplied environment providers.
160 */
161export function queryFeature(providers: EnvironmentProviders): QueryFeature {
162 const feature: InternalQueryFeature = {
163 [queryFeatureBrand]: true,
164 ɵproviders: providers,
165 }
166​
167 return feature
168}
169​
170/**
171 * Gets the environment providers owned by an opaque Query feature.
172 * @internal
173 * @param feature - The feature to unwrap.
174 * @returns The environment providers to install.
175 */
176export function getQueryFeatureProviders(
177 feature: QueryFeature,
178): EnvironmentProviders {
179 return (feature as InternalQueryFeature).ɵproviders
180}
181​
182/**
183 * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /
184 * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
185 * so each has its own key. The default key applies when you do not add this feature.
186 *
187 * ```ts
188 * providers: [
189 * provideTanStackQuery(
190 * () => new QueryClient(),
191 * withHydrationKey('my-secondary-query-cache'),
192 * ),
193 * ]
194 * ```
195 * @param key - A unique string for this client's `TransferState` entry.
196 * @returns A feature that stores this client's cache under the supplied key.
197 */
198export function withHydrationKey(key: string): QueryFeature {
199 return queryFeature(
200 makeEnvironmentProviders([
201 {
202 provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
203 useValue: makeStateKey<DehydratedState>(key),
204 },
205 ]),
206 )
207}
208​
209/**
210 * Disables `TransferState` hydration and dehydration for the current environment injector.
211 * @returns A feature that prevents automatic cache transfer for this injector.
212 */
213export function withNoQueryHydration(): QueryFeature {
214 return queryFeature(
215 makeEnvironmentProviders([
216 {
217 provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,
218 useValue: false,
219 },
220 ]),
221 )
222}