Open History to see the last commit
1---
2id: ssr
3title: SSR
4---
5β
6This guide covers using Solid Query with server rendering, specifically with [SolidStart](https://start.solidjs.com/).
7β
8If you haven't already, it's worth reading the [Prefetching & Router Integration](./prefetching.md) guide first.
9β
10## Solid Query's hydration model
11β
12Solid Query's `useQuery` is built on top of Solid's own [`createResource`](https://docs.solidjs.com/reference/basic-reactivity/create-resource), rather than a `dehydrate`/`hydrate` pair you call yourself. That has a consequence for this guide: **there is no `dehydrate`, `hydrate`, or `HydrationBoundary` in your application code.**
13β
14Instead, when `useQuery` runs on the server:
15β
161. It resolves the query through the same `QueryClient` cache a client render would use, with `retry` forced off and `throwOnError` forced on β see [Error handling](#error-handling) below.
172. The resolved value is a plain, serializable snapshot of the query result (functions like `refetch` are stripped, since they can't cross the network).
183. Solid's own resource streaming carries that snapshot down to the client β the same mechanism `createResource` uses for any async resource, query-related or not.
194. On the client, once the snapshot arrives, Solid Query hydrates the query cache from it internally, before your component ever sees a loading state for that query.
20β
21So the three steps you'd normally implement by hand β prefetch, dehydrate, hydrate β collapse into "call `useQuery` (or prefetch with `queryClient.query`), and let Solid's streaming take care of the rest." The tradeoff is that Solid Query decides what gets serialized and when, rather than you calling `dehydrate` with your own filtering logic.
22β
23One consequence worth calling out: a query that resolved on the server, and is read with a `staleTime` (or without `initialData`), does not refetch on mount when it hydrates on the client, since Solid Query already knows it has fresh-enough data from the server render. It behaves the same as any other successful query after that: `staleTime` governs whether it refetches on the next trigger (window focus, a new mount, `invalidateQueries`, and so on).
24β
25## Initial setup
26β
27As with any server-rendered app, create the `QueryClient` per request rather than at module scope, so cached data from one visitor's request is never shared with another's:
28β
29```tsx
30// src/app.tsx
31import { MetaProvider, Title } from '@solidjs/meta'
32import { Router } from '@solidjs/router'
33import { FileRoutes } from '@solidjs/start/router'
34import { Suspense } from 'solid-js'
35import { QueryClient, QueryClientProvider } from '@tanstack/solid-query'
36β
37export default function App() {
38 // Constructing the QueryClient inside the component (rather than at module
39 // scope) means SolidStart creates a fresh one for every request, so data
40 // is never shared between users.
41 const queryClient = new QueryClient({
42 defaultOptions: {
43 queries: {
44 // staleTime governs refetches from later triggers (a new mount, window
45 // focus, and so on) β see Solid Query's hydration model above for why
46 // the very first mount after SSR doesn't need it to skip a refetch.
47 staleTime: 5 * 1000,
48 },
49 },
50 })
51β
52 return (
53 <QueryClientProvider client={queryClient}>
54 <Router
55 root={(props) => (
56 <MetaProvider>
57 <Title>My App</Title>
58 <Suspense>{props.children}</Suspense>
59 </MetaProvider>
60 )}
61 >
62 <FileRoutes />
63 </Router>
64 </QueryClientProvider>
65 )
66}
67```
68β
69The `<Suspense>` boundary matters: `useQuery` suspends while a query is pending, both on the server (so SolidStart can wait for it, or stream past it) and on the client (during the very first render, before hydration data arrives).
70β
71## Using `useQuery` directly
72β
73Because hydration is automatic, the simplest way to get server-rendered data is to just call `useQuery` where you need it β no separate prefetch step required:
74β
75```tsx
76import { useQuery } from '@tanstack/solid-query'
77import { For, Suspense } from 'solid-js'
78β
79function Posts() {
80 const query = useQuery(() => ({
81 queryKey: ['posts'],
82 queryFn: fetchPosts,
83 }))
84β
85 return (
86 <Suspense fallback={<div>Loading...</div>}>
87 <ul>
88 <For each={query.data}>{(post) => <li>{post.title}</li>}</For>
89 </ul>
90 </Suspense>
91 )
92}
93```
94β
95On the server, this fetches `posts`, waits for it (because of the surrounding `<Suspense>`), and streams the resolved value down. On the client, that value hydrates the cache before `Posts` ever renders a loading state β as long as the client also renders inside a `<Suspense>` boundary, which the `<Suspense>` in `app.tsx` already provides.
96β
97Wrap the same query in Solid's `ErrorBoundary` to handle a failure. On the server, a failed query always throws to the nearest `ErrorBoundary` β see [Error handling](#error-handling) below for why, and for what it takes to get the same behavior on the client too:
98β
99```tsx
100import { useQuery } from '@tanstack/solid-query'
101import { ErrorBoundary, For, Suspense } from 'solid-js'
102β
103function Posts() {
104 const query = useQuery(() => ({
105 queryKey: ['posts'],
106 queryFn: fetchPosts,
107 }))
108β
109 return (
110 <ErrorBoundary
111 fallback={(err, reset) => (
112 <div>
113 <div>Error: {err.message}</div>
114 <button
115 onClick={async () => {
116 await query.refetch()
117 reset()
118 }}
119 >
120 Retry
121 </button>
122 </div>
123 )}
124 >
125 <Suspense fallback={<div>Loading...</div>}>
126 <ul>
127 <For each={query.data}>{(post) => <li>{post.title}</li>}</For>
128 </ul>
129 </Suspense>
130 </ErrorBoundary>
131 )
132}
133```
134β
135## Prefetching with `route.preload`
136β
137To prefetch a query from a SolidStart route's `preload` function, call `queryClient.query(...)`:
138β
139```tsx
140import { noop, useQueryClient } from '@tanstack/solid-query'
141β
142export const route = {
143 preload: () => {
144 const queryClient = useQueryClient()
145 queryClient.query(postsQueryOptions()).catch(noop)
146 },
147}
148β
149export default function Posts() {
150 const query = useQuery(() => postsQueryOptions())
151 // ...
152}
153```
154β
155`.catch(noop)` keeps a failed prefetch from aborting routing β whatever reads the query afterwards (`useQuery`) will surface the failure on its own. See [Error handling](#error-handling) below for how that failure surfaces differently on the server and the client.
156β
157Sharing the query options object (`postsQueryOptions()` above) between `route.preload` and the component that reads the data, rather than repeating the `queryKey`/`queryFn` in both places, keeps them from drifting apart β see [`queryOptions`](./query-options.md).
158β
159## Streaming with `deferStream`
160β
161By default, a query streams to the client as soon as it resolves on the server. Set `deferStream: true` to hold the server's response until that query resolves instead β useful for data that has to be present in the very first response, such as SEO meta tags:
162β
163```tsx
164const query = useQuery(() => ({
165 queryKey: ['user'],
166 queryFn: fetchUser,
167 deferStream: true,
168}))
169```
170β
171`deferStream` only affects when the _server_ flushes that query's chunk to the client. Setting it on every query on a page makes the server wait for all of them before sending anything.
172β
173## Error handling
174β
175On the server, `useQuery` always throws when a query fails β regardless of the `throwOnError` option β so it's caught by the nearest `<ErrorBoundary>` rather than surfacing as `query.isError`. This is different from the client, where a failed query reports `isError`/`error` unless you opt in to throwing with `throwOnError: true`. Retries are also disabled on the server, so a query throws on its first failure rather than retrying first.
176β
177If a query is read with `useQuery` on both the server and the client, set `throwOnError: true` on it explicitly so the client matches what the server already does β otherwise the same failure throws during SSR but only sets `isError` once it's running on the client:
178β
179```tsx
180const query = useQuery(() => ({
181 queryKey: ['user'],
182 queryFn: fetchUser,
183 throwOnError: true,
184}))
185```
186β
187A `route.preload` prefetch isn't affected by this server-only override β `queryClient.query(...)` doesn't take a `throwOnError` option at all, so it simply rejects when the query fails, the same on the server and the client. Catch it (or let it propagate) however fits the route; see [Prefetching with `route.preload`](#prefetching-with-routepreload) above for the `.catch(noop)` pattern used when a failed prefetch shouldn't abort routing.
188β
189## Tips, Tricks and Caveats
190β
191### Staleness is measured from when the query was fetched on the server
192β
193A query's staleness is based on `dataUpdatedAt`, which is set to when it resolved on the server, not when the client hydrates it. Because `staleTime` defaults to `0`, an SSR'd query without an explicit `staleTime` is treated as stale as soon as its next trigger (window focus, a new mount past the first one, `invalidateQueries`, and so on) checks it, and may refetch in the background then β the first mount on the client is still exempt, per [Solid Query's hydration model](#solid-querys-hydration-model) above. Setting a `staleTime` above `0` (as in the Initial setup example above) avoids this if you don't want it.
194β
195### High memory consumption on server
196β
197Because the `QueryClient` is created fresh for every request, its cache is held in memory for the duration of that request. Under high request volume this can add up. `gcTime` defaults to `Infinity` on the server, so unless you configure it lower, memory for a request's cache isn't reclaimed automatically β in most cases this is fine, since the whole `QueryClient` instance becomes eligible for garbage collection once the request finishes and nothing references it anymore.