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

spa-mode.md

249 lines7.7 KB

1---
2id: spa-mode
3title: SPA mode
4---
5​
6## What the heck is SPA mode?
7​
8For applications that do not require SSR for either SEO, crawlers, or performance reasons, it may be desirable to ship static HTML to your users containing the "shell" of your application (or even prerendered HTML for specific routes) that contain the necessary `html`, `head`, and `body` tags to bootstrap your application only on the client.
9​
10## Why use Start without SSR?
11​
12**No SSR doesn't mean giving up server-side features!** SPA modes actually pair very nicely with server-side features like server functions and/or server routes or even other external APIs. It **simply means that the initial document will not contain the fully rendered HTML of your application until it has been rendered on the client using JavaScript**.
13​
14## Benefits of SPA mode
15​
16- **Easier to deploy** - A CDN that can serve static assets is all you need.
17- **Cheaper** to host - CDNs are cheap compared to Lambda functions or long-running processes.
18- **Client-side Only is simpler** - No SSR means less to go wrong with hydration, rendering, and routing.
19​
20## Caveats of SPA mode
21​
22- **Slower time to full content** - Time to full content is longer since all JS must download and execute before anything below the shell can be rendered.
23- **Less SEO friendly** - Robots, crawlers and link unfurlers _may_ have a harder time indexing your application unless they are configured to execute JS and your application can render within a reasonable amount of time.
24​
25## How does it work?
26​
27After enabling the SPA mode, running a Start build will have an additional prerendering step afterwards to generate the shell. This is done by:
28​
29- **Prerendering** your application's **root route only**
30- Where your application would normally render your matched routes, your router's configured **pending fallback component is rendered instead**.
31- The resulting HTML is stored to a static HTML page called `/_shell.html` (configurable)
32- Default rewrites are configured to redirect all 404 requests to the SPA mode shell
33​
34> [!NOTE]
35> Other routes may also be prerendered and it is recommended to prerender as much as you can in SPA mode, but this is not required for SPA mode to work.
36​
37## Configuring SPA mode
38​
39To configure SPA mode, there are a few options you can add to your Start plugin's options:
40​
41<!-- ::start:tabs variant="bundler" -->
42​
43# Vite
44​
45```ts title="vite.config.ts"
46export default defineConfig({
47 plugins: [
48 tanstackStart({
49 spa: {
50 enabled: true,
51 },
52 }),
53 ],
54})
55```
56​
57# Rsbuild
58​
59```ts title="rsbuild.config.ts"
60export default defineConfig({
61 plugins: [
62 tanstackStart({
63 spa: {
64 enabled: true,
65 },
66 }),
67 ],
68})
69```
70​
71<!-- ::end:tabs -->
72​
73## Use Necessary Redirects
74​
75Deploying a purely client-side SPA to a host or CDN often requires the use of redirects to ensure that urls are properly rewritten to the SPA shell. The goal of any deployment should include these priorities in this order:
76​
771. Ensure that static assets will always be served if they exist, e.g. /about.html. This is usually the default behavior for most CDNs
782. (Optional) Allow-list specific subpaths to be routed through to any dynamic server handlers, e.g. /api/\*\* (More on this below)
793. Ensure that all 404 requests are rewritten to the SPA shell, e.g. a catch-all redirect to /\_shell.html (or if you have configured your shell output path to be something custom, use that instead)
80​
81## Basic Redirects Example
82​
83Let's use Netlify's `_redirects` file to rewrite all 404 requests to the SPA shell.
84​
85```
86# Catch all other 404 requests and rewrite them to the SPA shell
87/* /_shell.html 200
88```
89​
90## Allowing Server Functions and Server Routes
91​
92Again, using Netlify's `_redirects` file, we can allow-list specific subpaths to be routed through to the server.
93​
94```
95# Allow requests to /_serverFn/* to be routed through to the server (If you have configured your server function base path to be something other than /_serverFn, use that instead)
96/_serverFn/* /_serverFn/:splat 200
97​
98# Allow any requests to /api/* to be routed through to the server (Server routes can be created at any path, so you must ensure that any server routes you want to use are under this path, or simply add additional redirects for each server route base you want to expose)
99/api/* /api/:splat 200
100​
101# Catch all other 404 requests and rewrite them to the SPA shell
102/* /_shell.html 200
103```
104​
105## Shell Mask Path
106​
107The default pathname used to generate the SPA shell is `/`. We call this the **shell mask path**. Since matched routes are not included, the pathname used to generate the shell is mostly irrelevant, but it's still configurable.
108​
109> [!NOTE]
110> It's recommended to keep the default value of `/` as the shell mask path.
111​
112<!-- ::start:tabs variant="bundler" -->
113​
114# Vite
115​
116```ts title="vite.config.ts"
117export default defineConfig({
118 plugins: [
119 tanstackStart({
120 spa: {
121 maskPath: '/app',
122 },
123 }),
124 ],
125})
126```
127​
128# Rsbuild
129​
130```ts title="rsbuild.config.ts"
131export default defineConfig({
132 plugins: [
133 tanstackStart({
134 spa: {
135 maskPath: '/app',
136 },
137 }),
138 ],
139})
140```
141​
142<!-- ::end:tabs -->
143​
144## Prerendering Options
145​
146The prerender option is used to configure the prerendering behavior of the SPA shell, and accepts the same prerender options as found in our prerendering guide.
147​
148**By default, the following `prerender` options are set:**
149​
150- `outputPath`: `/_shell.html`
151- `crawlLinks`: `false`
152- `retryCount`: `0`
153​
154This means that by default, the shell will not be crawled for links to follow for additional prerendering, and will not retry prerendering fails.
155​
156You can always override these options by providing your own prerender options:
157​
158<!-- ::start:tabs variant="bundler" -->
159​
160# Vite
161​
162```ts title="vite.config.ts"
163export default defineConfig({
164 plugins: [
165 tanstackStart({
166 spa: {
167 prerender: {
168 outputPath: '/custom-shell',
169 crawlLinks: true,
170 retryCount: 3,
171 },
172 },
173 }),
174 ],
175})
176```
177​
178# Rsbuild
179​
180```ts title="rsbuild.config.ts"
181export default defineConfig({
182 plugins: [
183 tanstackStart({
184 spa: {
185 prerender: {
186 outputPath: '/custom-shell',
187 crawlLinks: true,
188 retryCount: 3,
189 },
190 },
191 }),
192 ],
193})
194```
195​
196<!-- ::end:tabs -->
197​
198## Customized rendering in SPA mode
199​
200Customizing the HTML output of the SPA shell can be useful if you want to:
201​
202- Provide generic head tags for SPA routes
203- Provide a custom pending fallback component
204- Change literally anything about the shell's HTML, CSS, and JS
205​
206To make this process simple, an `isShell()` function can be found on the `router` instance:
207​
208```tsx
209// src/routes/root.tsx
210export default function Root() {
211 const isShell = useRouter().isShell()
212​
213 if (isShell) console.log('Rendering the shell!')
215```
216​
217You can use this boolean to conditionally render different UI based on whether the current route is a shell or not, but keep in mind that after hydrating the shell, the router will immediately navigate to the first route and `isShell()` will return `false`. **This could produce flashes of unstyled content if not handled properly.**
218​
219## Dynamic Data in your Shell
220​
221Since the shell is prerendered using the SSR build of your application, any `loader`s, or server-specific functionality defined on your **Root Route** will run during the prerendering process and the data will be included in the shell.
222​
223This means that you can use dynamic data in your shell by using a `loader` or server-specific functionality.
224​
225```tsx
226// src/routes/__root.tsx
227​
228export const RootRoute = createRootRoute({
229 loader: async () => {
230 return {
231 name: 'Tanner',
232 }
233 },
234 component: Root,
235})
236​
237export default function Root() {
238 const { name } = useLoaderData()
239​
240 return (
241 <html>
242 <body>
243 <h1>Hello, {name}!</h1>
244 <Outlet />
245 </body>
246 </html>
247 )
249```