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```markdown
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/svelte/ssr).
38β
39β
40### Using `initialData`
41β
42Together with SvelteKit's [`load`](https://kit.svelte.dev/docs/load), you can pass the data loaded server-side into `createQuery`'s' `initialData` option:
43β
44**src/routes/+page.ts**
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```markdown
56<script>
57 import { createQuery } from '@tanstack/svelte-query'
58 import type { PageData } from './$types'
59β
60 export let data: PageData
61β
62 const query = createQuery({
63 queryKey: ['posts'],
64 queryFn: getPosts,
65 initialData: data.posts
66 })
67</script>
68```
69β
70Pros:
71β
72- This setup is minimal and this can be a quick solution for some cases
73- Works with both `+page.ts`/`+layout.ts` and `+page.server.ts`/`+layout.server.ts` load functions
74β
75Cons:
76β
77- If you are calling `createQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
78- If you are calling `createQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
79- 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
80β
81### Using `prefetchQuery`
82β
83Svelte 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.
84β
85**src/routes/+layout.ts**
86β
87```ts
88import { browser } from '$app/environment'
89import { QueryClient } from '@tanstack/svelte-query'
90import type { LayoutLoad } from './$types'
91β
92export const load: LayoutLoad = 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```markdown
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```markdown
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)