Open History to see the last commit
1---
2id: ssr
3title: Server Rendering & Hydration
4---
5β
6Lit Query can be used with server rendering by combining Lit SSR with TanStack Query Core hydration APIs re-exported from `@tanstack/lit-query`.
7β
8The runnable source for this guide is the [SSR example](../examples/ssr).
9β
10## Flow
11β
12Server rendering has three phases:
13β
141. Create a per-request `QueryClient`.
152. Prefetch queries on the server and render Lit HTML with that client.
163. Dehydrate the cache into the HTML, then hydrate a browser `QueryClient` before the client app renders.
17β
18Never share one server `QueryClient` between users or requests.
19β
20## Server Prefetch and Render
21β
22```ts
23import { render } from '@lit-labs/ssr'
24import { collectResult } from '@lit-labs/ssr/lib/render-result.js'
25import { html } from 'lit'
26import { QueryClient, dehydrate, noop } from '@tanstack/lit-query'
27import { createDataQueryOptions } from './api.js'
28import './app.js'
29β
30async function renderPage() {
31 const apiBaseUrl = 'https://example.com'
32 const queryClient = new QueryClient({
33 defaultOptions: {
34 queries: {
35 staleTime: 30_000,
36 },
37 },
38 })
39β
40 await queryClient.query(createDataQueryOptions(apiBaseUrl)).catch(noop)
41β
42 const appHtml = await collectResult(
43 render(
44 html`<ssr-app
45 api-base-url=${apiBaseUrl}
46 .queryClient=${queryClient}
47 ></ssr-app>`,
48 ),
49 )
50β
51 const dehydratedState = dehydrate(queryClient)
52β
53 return { appHtml, dehydratedState }
54}
55```
56β
57The server passes the same client into the Lit element with a property binding. This lets `createQueryController` read the prefetched cache during server render. If your query function calls `fetch` during SSR, pass an absolute API origin instead of relying on a browser-relative URL.
58β
59## Client Hydration
60β
61```ts
62import '@lit-labs/ssr-client/lit-element-hydrate-support.js'
63import { QueryClient, hydrate, type DehydratedState } from '@tanstack/lit-query'
64β
65const queryClient = new QueryClient({
66 defaultOptions: {
67 queries: {
68 staleTime: 30_000,
69 },
70 },
71})
72β
73const dehydratedState = JSON.parse(
74 document.getElementById('__QUERY_STATE__')?.textContent ?? 'null',
75) as DehydratedState
76β
77queryClient.mount()
78hydrate(queryClient, dehydratedState)
79β
80const appElement = document.querySelector('ssr-app') as
81 | (HTMLElement & { queryClient?: QueryClient })
82 | null
83β
84if (!appElement) {
85 throw new Error('Expected the SSR app element to exist before hydration.')
86}
87β
88appElement.queryClient = queryClient
89await import('./app.js')
90```
91β
92Unmount the client when the page is unloaded if you mounted it manually:
93β
94```ts
95window.addEventListener(
96 'pagehide',
97 () => {
98 queryClient.unmount()
99 },
100 { once: true },
101)
102```
103β
104## Component Pattern
105β
106The SSR example creates its controller only after a `queryClient` property is available:
107β
108```ts
109import { LitElement } from 'lit'
110import {
111 createQueryController,
112 type QueryClient,
113 type QueryResultAccessor,
114} from '@tanstack/lit-query'
115import { createDataQueryOptions, type DataResponse } from './api.js'
116β
117class SsrApp extends LitElement {
118 static properties = {
119 apiBaseUrl: { attribute: 'api-base-url' },
120 queryClient: { attribute: false },
121 }
122β
123 apiBaseUrl = ''
124 queryClient?: QueryClient
125 private dataQuery?: QueryResultAccessor<DataResponse, Error>
126β
127 protected override willUpdate(): void {
128 if (!this.dataQuery && this.queryClient) {
129 this.dataQuery = createQueryController(
130 this,
131 createDataQueryOptions(this.apiBaseUrl),
132 this.queryClient,
133 )
134 }
135 }
136}
137```
138β
139This explicit-client pattern is useful for SSR because the client is created by the renderer rather than discovered from a connected DOM provider.
140β
141## Serialization
142β
143Embed dehydrated state as JSON in the HTML and escape characters that can break out of a script tag. The example server uses a small serializer before replacing `__QUERY_STATE_JSON__` in the built HTML template.
144β
145Lit Query re-exports `dehydrate` and `hydrate` from TanStack Query Core. Use `dehydrate(queryClient)` after server prefetching to capture the cache state. In the browser, parse that state, create a fresh `QueryClient`, call `hydrate(queryClient, dehydratedState)`, assign the client to the server-rendered element, and only then import the Lit component so it upgrades with the prefetched cache available.