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
46export async function load() {
47 const posts = await getPosts()
48 return { posts }
49}
50```
51β
52**src/routes/+page.svelte**
53β
54```svelte
55<script>
56 import { createQuery } from '@tanstack/svelte-query'
57 import type { PageData } from './$types'
58β
59 export let data: PageData
60β
61 const query = createQuery(() => ({
62 queryKey: ['posts'],
63 queryFn: getPosts,
64 initialData: data.posts,
65 }))
66</script>
67```
68β
69Pros:
70β
71- This setup is minimal and this can be a quick solution for some cases
72- Works with both `+page.ts`/`+layout.ts` and `+page.server.ts`/`+layout.server.ts` load functions
73β
74Cons:
75β
76- If you are calling `createQuery` in a component deeper down in the tree you need to pass the `initialData` down to that point
77- If you are calling `createQuery` with the same query in multiple locations, you need to pass `initialData` to all of them
78- 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
79β
80### Using `prefetchQuery`
81β
82Svelte 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.
83β
84**src/routes/+layout.ts**
85β
86```ts
87import { browser } from '$app/environment'
88import { QueryClient } from '@tanstack/svelte-query'
89β
90export async function load() {
91 const queryClient = new QueryClient({
92 defaultOptions: {
93 queries: {
94 enabled: browser,
95 },
96 },
97 })
98β
99 return { queryClient }
100}
101```
102β
103**src/routes/+layout.svelte**
104β
105```svelte
106<script lang="ts">
107 import { QueryClientProvider } from '@tanstack/svelte-query'
108 import type { LayoutData } from './$types'
109β
110 export let data: LayoutData
111</script>
112β
113<QueryClientProvider client={data.queryClient}>
114 <slot />
115</QueryClientProvider>
116```
117β
118**src/routes/+page.ts**
119β
120```ts
121export async function load({ parent, fetch }) {
122 const { queryClient } = await parent()
123β
124 // You need to use the SvelteKit fetch function here
125 await queryClient.prefetchQuery({
126 queryKey: ['posts'],
127 queryFn: async () => (await fetch('/api/posts')).json(),
128 })
129}
130```
131β
132**src/routes/+page.svelte**
133β
134```svelte
135<script lang="ts">
136 import { createQuery } from '@tanstack/svelte-query'
137β
138 // This data is cached by prefetchQuery in +page.ts so no fetch actually happens here
139 const query = createQuery(() => ({
140 queryKey: ['posts'],
141 queryFn: async () => (await fetch('/api/posts')).json(),
142 }))
143</script>
144```
145β
146Pros:
147β
148- Server-loaded data can be accessed anywhere without prop-drilling
149- 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`
150β
151Cons:
152β
153- Requires more files for initial setup
154- 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)