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.prefetchQuery()`, 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 const queryClient = new QueryClient({
20 defaultOptions: {
21 queries: {
22 enabled: browser,
23 },
24 },
25 })
26</script>
27β
28<QueryClientProvider client={queryClient}>
29 <slot />
30</QueryClientProvider>
31```
32β
33## Prefetching data
34β
35Svelte Query supports two ways of prefetching data on the server and passing that to the client with SvelteKit.
36β
37If you wish to view the ideal SSR setup, please have a look at the [SSR example](./examples/ssr).
38β
39### Using `initialData`
40β
41Together with SvelteKit's [`load`](https://kit.svelte.dev/docs/load), you can pass the data loaded server-side into `createQuery`'s' `initialData` option:
42β
43**src/routes/+page.ts**
44β
45```ts
46import type { PageLoad } from './$types'
47β
48export const load: PageLoad = async () => {
49 const posts = await getPosts()
50 return { posts }
51}
52```
53β
54**src/routes/+page.svelte**
55β
56```svelte
57<script>
58 import { createQuery } from '@tanstack/svelte-query'
59 import type { PageData } from './$types'
60β
61 export let data: PageData
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 `prefetchQuery`
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 const load = async () => {
93 const queryClient = new QueryClient({
94 defaultOptions: {
95 queries: {
96 enabled: browser,
97 },
98 },
99 })
100β
101 return { queryClient }
102}
103```
104β
105**src/routes/+layout.svelte**
106β
107```svelte
108<script lang="ts">
109 import { QueryClientProvider } from '@tanstack/svelte-query'
110 import type { LayoutData } from './$types'
111β
112 export let data: LayoutData
113</script>
114β
115<QueryClientProvider client={data.queryClient}>
116 <slot />
117</QueryClientProvider>
118```
119β
120**src/routes/+page.ts**
121β
122```ts
123import type { PageLoad } from './$types'
124β
125export const load: PageLoad = async ({ parent, fetch }) => {
126 const { queryClient } = await parent()
127β
128 // You need to use the SvelteKit fetch function here
129 await queryClient.prefetchQuery({
130 queryKey: ['posts'],
131 queryFn: async () => (await fetch('/api/posts')).json(),
132 })
133}
134```
135β
136**src/routes/+page.svelte**
137β
138```svelte
139<script lang="ts">
140 import { createQuery } from '@tanstack/svelte-query'
141β
142 // This data is cached by prefetchQuery in +page.ts so no fetch actually happens here
143 const query = createQuery({
144 queryKey: ['posts'],
145 queryFn: async () => (await fetch('/api/posts')).json(),
146 })
147</script>
148```
149β
150Pros:
151β
152- Server-loaded data can be accessed anywhere without prop-drilling
153- 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`
154β
155Cons:
156β
157- Requires more files for initial setup
158- 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)