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 { dataQueries } from './services/data/queries.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 * 1000,
36 },
37 },
38 })
39β
40 await queryClient.query(dataQueries.detail(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 } from '@tanstack/lit-query'
64import type { DehydratedState } from '@tanstack/lit-query'
65β
66const queryClient = new QueryClient({
67 defaultOptions: {
68 queries: {
69 staleTime: 30 * 1000,
70 },
71 },
72})
73β
74const dehydratedState = JSON.parse(
75 document.getElementById('__QUERY_STATE__')?.textContent ?? 'null',
76) as DehydratedState
77β
78queryClient.mount()
79hydrate(queryClient, dehydratedState)
80β
81const appElement = document.querySelector('ssr-app') as
82 | (HTMLElement & { queryClient?: QueryClient })
83 | null
84β
85if (!appElement) {
86 throw new Error('Expected the SSR app element to exist before hydration.')
87}
88β
89appElement.queryClient = queryClient
90await import('./app.js')
91```
92β
93Unmount the client when the page is unloaded if you mounted it manually:
94β
95```ts
96window.addEventListener(
97 'pagehide',
98 () => {
99 queryClient.unmount()
100 },
101 { once: true },
102)
103```
104β
105## Component Pattern
106β
107The SSR example creates its controller only after a `queryClient` property is available:
108β
109```ts
110import { LitElement } from 'lit'
111import { createQueryController } from '@tanstack/lit-query'
112import { dataQueries } from './services/data/queries.js'
113import type { QueryClient, QueryResultAccessor } from '@tanstack/lit-query'
114import type { DataResponse } from './services/data/types.js'
115β
116class SsrApp extends LitElement {
117 static properties = {
118 apiBaseUrl: { attribute: 'api-base-url' },
119 queryClient: { attribute: false },
120 }
121β
122 apiBaseUrl = ''
123 queryClient?: QueryClient
124 private dataQuery?: QueryResultAccessor<DataResponse, Error>
125β
126 protected override willUpdate(): void {
127 if (!this.dataQuery && this.queryClient) {
128 this.dataQuery = createQueryController(
129 this,
130 dataQueries.detail(this.apiBaseUrl),
131 this.queryClient,
132 )
133 }
134 }
135}
136```
137β
138This explicit-client pattern is useful for SSR because the client is created by the renderer rather than discovered from a connected DOM provider.
139β
140## Serialization
141β
142Embed 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.
143β
144Lit 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.