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

selective-ssr.md

228 lines8.2 KB

1---
2id: selective-ssr
3title: Selective Server-Side Rendering (SSR)
4---
5​
6## What is Selective SSR?
7​
8In TanStack Start, routes matching the initial request are rendered on the server by default. This means `beforeLoad` and `loader` are executed on the server, followed by rendering the route components. The resulting HTML is sent to the client, which hydrates the markup into a fully interactive application.
9​
10However, there are cases where you might want to disable SSR for certain routes or all routes, such as:
11​
12- When `beforeLoad` or `loader` requires browser-only APIs (e.g., `localStorage`).
13- When the route component depends on browser-only APIs (e.g., `canvas`).
14​
15TanStack Start's Selective SSR feature lets you configure:
16​
17- Which routes should execute `beforeLoad` or `loader` on the server.
18- Which route components should be rendered on the server.
19​
20## How does this compare to SPA mode?
21​
22TanStack Start's [SPA mode](./spa-mode) completely disables server-side execution of `beforeLoad` and `loader`, as well as server-side rendering of route components. Selective SSR allows you to configure server-side handling on a per-route basis, either statically or dynamically.
23​
24## Configuration
25​
26You can control how a route is handled during the initial server request using the `ssr` property. If this property is not set, it defaults to `true`. You can change this default using the `defaultSsr` option in `createStart`:
27​
28```tsx
29// src/start.ts
30import { createStart } from '@tanstack/react-start'
31​
32export const startInstance = createStart(() => ({
33 // Disable SSR by default
34 defaultSsr: false,
35}))
36```
37​
38### `ssr: true`
39​
40This is the default behavior unless otherwise configured. On the initial request, it will:
41​
42- Run `beforeLoad` on the server and send the resulting context to the client.
43- Run `loader` on the server and send the loader data to the client.
44- Render the component on the server and send the HTML markup to the client.
45​
46```tsx
47// src/routes/posts/$postId.tsx
48export const Route = createFileRoute('/posts/$postId')({
49 ssr: true,
50 beforeLoad: () => {
51 console.log('Executes on the server during the initial request')
52 console.log('Executes on the client for subsequent navigation')
53 },
54 loader: () => {
55 console.log('Executes on the server during the initial request')
56 console.log('Executes on the client for subsequent navigation')
57 },
58 component: () => <div>This component is rendered on the server</div>,
59})
60```
61​
62### `ssr: false`
63​
64This disables server-side:
65​
66- Execution of the route's `beforeLoad` and `loader`.
67- Rendering of the route component.
68​
69```tsx
70// src/routes/posts/$postId.tsx
71export const Route = createFileRoute('/posts/$postId')({
72 ssr: false,
73 beforeLoad: () => {
74 console.log('Executes on the client during hydration')
75 },
76 loader: () => {
77 console.log('Executes on the client during hydration')
78 },
79 component: () => <div>This component is rendered on the client</div>,
80})
81```
82​
83### `ssr: 'data-only'`
84​
85This hybrid option will:
86​
87- Run `beforeLoad` on the server and send the resulting context to the client.
88- Run `loader` on the server and send the loader data to the client.
89- Disable server-side rendering of the route component.
90​
91```tsx
92// src/routes/posts/$postId.tsx
93export const Route = createFileRoute('/posts/$postId')({
94 ssr: 'data-only',
95 beforeLoad: () => {
96 console.log('Executes on the server during the initial request')
97 console.log('Executes on the client for subsequent navigation')
98 },
99 loader: () => {
100 console.log('Executes on the server during the initial request')
101 console.log('Executes on the client for subsequent navigation')
102 },
103 component: () => <div>This component is rendered on the client</div>,
104})
105```
106​
107### Functional Form
108​
109For more flexibility, you can use the functional form of the `ssr` property to decide at runtime whether to SSR a route:
110​
111```tsx
112// src/routes/docs/$docType/$docId.tsx
113export const Route = createFileRoute('/docs/$docType/$docId')({
114 validateSearch: z.object({ details: z.boolean().optional() }),
115 ssr: ({ params, search }) => {
116 if (params.status === 'success' && params.value.docType === 'sheet') {
117 return false
118 }
119 if (search.status === 'success' && search.value.details) {
120 return 'data-only'
121 }
122 },
123 beforeLoad: () => {
124 console.log('Executes on the server depending on the result of ssr()')
125 },
126 loader: () => {
127 console.log('Executes on the server depending on the result of ssr()')
128 },
129 component: () => <div>This component is rendered on the client</div>,
130})
131```
132​
133The `ssr` function runs only on the server during the initial request and is stripped from the client bundle.
134​
135`search` and `params` are passed in after validation as a discriminated union:
136​
137```tsx
138params:
139 | { status: 'success'; value: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>> }
140 | { status: 'error'; error: unknown }
141search:
142 | { status: 'success'; value: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> }
143 | { status: 'error'; error: unknown }
144```
145​
146If validation fails, `status` will be `error` and `error` will contain the failure details. Otherwise, `status` will be `success` and `value` will contain the validated data.
147​
148### Inheritance
149​
150At runtime, a child route inherits the Selective SSR configuration of its parent. However, the inherited value can only be changed to be more restrictive (i.e. `true` to `data-only` or `false` and `data-only` to `false`). For example:
151​
152```tsx
153root { ssr: undefined }
154 posts { ssr: false }
155 $postId { ssr: true }
156```
157​
158- `root` defaults to `ssr: true`.
159- `posts` explicitly sets `ssr: false`, so neither `beforeLoad` nor `loader` will run on the server, and the route component won't be rendered on the server.
160- `$postId` sets `ssr: true`, but inherits `ssr: false` from its parent. Because the inherited value can only be changed to be more restrictive, `ssr: true` has no effect and the inherited `ssr: false` will remain.
161​
162Another example:
163​
164```tsx
165root { ssr: undefined }
166 posts { ssr: 'data-only' }
167 $postId { ssr: true }
168 details { ssr: false }
169```
170​
171- `root` defaults to `ssr: true`.
172- `posts` sets `ssr: 'data-only'`, so `beforeLoad` and `loader` run on the server, but the route component isn't rendered on the server.
173- `$postId` sets `ssr: true`, but inherits `ssr: 'data-only'` from its parent.
174- `details` sets `ssr: false`, so neither `beforeLoad` nor `loader` will run on the server, and the route component won't be rendered on the server. Here the inherited value is changed to be more restrictive, and therefore, the `ssr: false` will override the inherited value.
175​
176## Fallback Rendering
177​
178For the first route with `ssr: false` or `ssr: 'data-only'`, the server will render the route's `pendingComponent` as a fallback. If `pendingComponent` isn't configured, the `defaultPendingComponent` will be rendered. If neither is configured, no fallback will be rendered.
179​
180On the client during hydration, this fallback will be displayed for at least `minPendingMs` (or `defaultPendingMinMs` if not configured), even if the route doesn't have `beforeLoad` or `loader` defined.
181​
182## How to disable SSR of the root route?
183​
184You can disable server side rendering of the root route component, however the `<html>` shell still needs to be rendered on the server. This shell is configured via the `shellComponent` property and takes a single property `children`. The `shellComponent` is always SSRed and is wrapping around the root `component`, the root `errorComponent` or the root `notFound` component respectively.
185​
186A minimal setup of a root route with disabled SSR for the route component looks like this:
187​
188```tsx
189import * as React from 'react'
190​
191import {
192 HeadContent,
193 Outlet,
194 Scripts,
195 createRootRoute,
196} from '@tanstack/react-router'
197​
198export const Route = createRootRoute({
199 shellComponent: RootShell,
200 component: RootComponent,
201 errorComponent: () => <div>Error</div>,
202 notFoundComponent: () => <div>Not found</div>,
203 ssr: false, // or `defaultSsr: false` on the router
204})
205​
206function RootShell({ children }: { children: React.ReactNode }) {
207 return (
208 <html>
209 <head>
210 <HeadContent />
211 </head>
212 <body>
213 {children}
214 <Scripts />
215 </body>
216 </html>
217 )
219​
220function RootComponent() {
221 return (
222 <div>
223 <h1>This component will be rendered on the client</h1>
224 <Outlet />
225 </div>
226 )
228```