Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

ssr.md

145 lines4.2 KB

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 }
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.')
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 },
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 }
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.