Open History to see the last commit
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 }
51}
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 }
105}
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)
138}
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)