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

ssr.md

163 lines4.6 KB

1---
2id: overview
3title: SSR and SvelteKit
4---
5​
6## Setup
7​
8SvelteKit defaults to rendering routes with SSR. Because of this, you need to disable the query on the server. Otherwise, your query will continue executing on the server asynchronously, even after the HTML has been sent to the client.
9​
10The recommended way to achieve this is to use the `browser` module from SvelteKit in your `QueryClient` object. This will not disable `queryClient.query()`, which is used in one of the solutions below.
11​
12**src/routes/+layout.svelte**
13​
14```svelte
15<script lang="ts">
16 import { browser } from '$app/environment'
17 import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query'
18​
19 let { children } = $props()
20​
21 const queryClient = new QueryClient({
22 defaultOptions: {
23 queries: {
24 enabled: browser,
25 },
26 },
27 })
28</script>
29​
30<QueryClientProvider client={queryClient}>
31 {@render children()}
32</QueryClientProvider>
33```
34​
35## Prefetching data
36​
37Svelte Query supports two ways of prefetching data on the server and passing that to the client with SvelteKit.
38​
39If you wish to view the ideal SSR setup, please have a look at the [SSR example](./examples/ssr-sveltekit).
40​
41### Using `initialData`
42​
43Together with SvelteKit's [`load`](https://kit.svelte.dev/docs/load), you can pass the data loaded server-side into `createQuery`'s' `initialData` option:
44​
45**src/routes/+page.ts**
46​
47```ts
48export async function load() {
49 const posts = await getPosts()
50 return { posts }
52```
53​
54**src/routes/+page.svelte**
55​
56```svelte
57<script lang="ts">
58 import { createQuery } from '@tanstack/svelte-query'
59 import type { PageProps } from './$types'
60​
61 let { data }: PageProps = $props()
62​
63 const query = createQuery(() => ({
64 queryKey: ['posts'],
65 queryFn: getPosts,
66 initialData: data.posts,
67 }))
68</script>
69```
70​
71Pros:
72​
73- This setup is minimal and this can be a quick solution for some cases
74- Works with both `+page.ts`/`+layout.ts` and `+page.server.ts`/`+layout.server.ts` load functions
75​
76Cons:
77​
78- If you are calling `createQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
79- If you are calling `createQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
80- There is no way to know at what time the query was fetched on the server, so `dataUpdatedAt` and determining if the query needs refetching is based on when the page loaded instead
81​
82### Using `query`
83​
84Svelte Query supports prefetching queries on the server. Using this setup below, you can fetch data and pass it into QueryClientProvider before it is sent to the user's browser. Therefore, this data is already available in the cache, and no initial fetch occurs client-side.
85​
86**src/routes/+layout.ts**
87​
88```ts
89import { browser } from '$app/environment'
90import { QueryClient } from '@tanstack/svelte-query'
91​
92export async function load() {
93 const queryClient = new QueryClient({
94 defaultOptions: {
95 queries: {
96 enabled: browser,
97 // With SSR, we usually want to set some default staleTime
98 // above 0 to avoid refetching immediately on the client
99 staleTime: 60 * 1000,
100 },
101 },
102 })
103​
104 return { queryClient }
106```
107​
108**src/routes/+layout.svelte**
109​
110```svelte
111<script lang="ts">
112 import { QueryClientProvider } from '@tanstack/svelte-query'
113 import type { LayoutProps } from './$types'
114​
115 let { data, children }: LayoutProps = $props()
116</script>
117​
118<QueryClientProvider client={data.queryClient}>
119 {@render children()}
120</QueryClientProvider>
121```
122​
123**src/routes/+page.ts**
124​
125```ts
126import { noop } from '@tanstack/svelte-query'
127​
128export async function load({ parent, fetch }) {
129 const { queryClient } = await parent()
130​
131 // You need to use the SvelteKit fetch function here
132 await queryClient
133 .query({
134 queryKey: ['posts'],
135 queryFn: async () => (await fetch('/api/posts')).json(),
136 })
137 .catch(noop)
139```
140​
141**src/routes/+page.svelte**
142​
143```svelte
144<script lang="ts">
145 import { createQuery } from '@tanstack/svelte-query'
146​
147 // This data is cached by query in +page.ts so no fetch actually happens here
148 const query = createQuery(() => ({
149 queryKey: ['posts'],
150 queryFn: async () => (await fetch('/api/posts')).json(),
151 }))
152</script>
153```
154​
155Pros:
156​
157- Server-loaded data can be accessed anywhere without prop-drilling
158- No initial fetch occurs client-side once the page is rendered, as the query cache retains all information about the query was made including `dataUpdatedAt`
159​
160Cons:
161​
162- Requires more files for initial setup
163- Will not work with `+page.server.ts`/`+layout.server.ts` load functions (however, APIs which are used with TanStack Query need to be fully exposed to the browser anyway)