INDIE UNPKG

10.1 kBMarkdownView Raw
1---
2title: Pre-Rendering
3---
4
5# Pre-Rendering
6
7[MODES: framework]
8
9<br/>
10<br/>
11
12Pre-Rendering allows you to speed up page loads for static content by rendering pages at build time instead of at runtime.
13
14## Configuration
15
16Pre-rendering is enabled via the `prerender` config in `react-router.config.ts`.
17
18The simplest configuration is a boolean `true` which will pre-render all off the applications static paths based on `routes.ts`:
19
20```ts filename=react-router.config.ts
21import type { Config } from "@react-router/dev/config";
22
23export default {
24 prerender: true,
25} satisfies Config;
26```
27
28The boolean `true` will not include any dynamic paths (i.e., `/blog/:slug`) because the parameter values are unknown.
29
30To configure specific paths including dynamic values, you can specify an array of paths:
31
32```ts filename=react-router.config.ts
33import type { Config } from "@react-router/dev/config";
34
35let slugs = getPostSlugs();
36
37export default {
38 prerender: [
39 "/",
40 "/blog",
41 ...slugs.map((s) => `/blog/${s}`),
42 ],
43} satisfies Config;
44```
45
46If you need to perform more complex and/or asynchronous logic to determine the paths, you can also provide a function that returns an array of paths. This function provides you with a `getStaticPaths` method you can use to avoid manually adding all of the static paths in your application:
47
48```ts filename=react-router.config.ts
49import type { Config } from "@react-router/dev/config";
50
51export default {
52 async prerender({ getStaticPaths }) {
53 let slugs = await getPostSlugsFromCMS();
54 return [
55 ...getStaticPaths(), // "/" and "/blog"
56 ...slugs.map((s) => `/blog/${s}`),
57 ];
58 },
59} satisfies Config;
60```
61
62### Concurrency
63
64By default, pages are pre-rendered one path at a time. You can enable concurrency to pre-render multiple paths in parallel which can speed up build times in many cases. You should experiment with the value that provides the best performance for your app.
65
66To specify concurrency, move your `prerender` config down into a `prerender.paths` field and you can specify the concurrency in `prerender.concurrency`:
67
68```ts filename=react-router.config.ts
69import type { Config } from "@react-router/dev/config";
70
71let slugs = getPostSlugs();
72
73export default {
74 prerender: {
75 paths: [
76 "/",
77 "/blog",
78 ...slugs.map((s) => `/blog/${s}`),
79 ],
80 concurrency: 4,
81 },
82} satisfies Config;
83```
84
85## Pre-Rendering with/without a Runtime Server
86
87Pre-Rendering can be used with these `ssr` config values:
88
89- Alongside a runtime SSR server with `ssr:true` (the default value)
90- Deployed to a static file server with `ssr:false`
91- Alongside a runtime API server with `ssr:"unstable_api-only"` (experimental)
92
93### Pre-rendering with `ssr:true`
94
95When pre-rendering with `ssr:true`, you're indicating you will still have a runtime server but you are choosing to pre-render certain paths for quicker Response times.
96
97```ts filename=react-router.config.ts
98import type { Config } from "@react-router/dev/config";
99
100export default {
101 // Can be omitted - defaults to true
102 ssr: true,
103 prerender: ["/", "/blog", "/blog/popular-post"],
104} satisfies Config;
105```
106
107#### Data Loading and Pre-rendering
108
109There is no extra application API for pre-rendering. Routes being pre-rendered use the same route `loader` functions as server rendering:
110
111```tsx
112export async function loader({ request, params }) {
113 let post = await getPost(params.slug);
114 return post;
115}
116
117export function Post({ loaderData }) {
118 return <div>{loaderData.title}</div>;
119}
120```
121
122Instead of a request coming to your route on a deployed server, the build creates a `new Request()` and runs it through your app just like a server would.
123
124When server rendering, requests to paths that have not been pre-rendered will be server rendered as usual.
125
126#### Static File Output
127
128The rendered result will be written out to your `build/client` directory. You'll notice two files for each path:
129
130- `[url].html` HTML file for initial document requests
131- `[url].data` file for client side navigation browser requests
132
133The output of your build will indicate what files were pre-rendered:
134
135```sh
136> react-router build
137vite v5.2.11 building for production...
138...
139vite v5.2.11 building SSR bundle for production...
140...
141Prerender: Generated build/client/index.html
142Prerender: Generated build/client/blog.data
143Prerender: Generated build/client/blog/index.html
144Prerender: Generated build/client/blog/my-first-post.data
145Prerender: Generated build/client/blog/my-first-post/index.html
146...
147```
148
149During development, pre-rendering doesn't save the rendered results to the public directory, this only happens for `react-router build`.
150
151### Pre-rendering with `ssr:false`
152
153The above examples assume you are deploying a runtime server but are pre-rendering some static pages to avoid hitting the server, resulting in faster loads.
154
155To disable runtime SSR and configure pre-rendering to be served from a static file server, you can set the `ssr:false` config flag:
156
157```ts filename=react-router.config.ts
158import type { Config } from "@react-router/dev/config";
159
160export default {
161 ssr: false, // disable runtime server rendering
162 prerender: true, // pre-render all static routes
163} satisfies Config;
164```
165
166If you specify `ssr:false` without a `prerender` config, React Router refers to that as [SPA Mode](./spa). In SPA Mode, we render a single HTML file that is capable of hydrating for _any_ of your application paths. It can do this because it only renders the `root` route into the HTML file and then determines which child routes to load based on the browser URL during hydration. This means you can use a `loader` on the root route, but not on any other routes because we don't know which routes to load until hydration in the browser.
167
168If you want to pre-render paths with `ssr:false`, those matched routes _can_ have loaders because we'll pre-render all of the matched routes for those paths, not just the root. You cannot include `actions` or `headers` functions in any routes when `ssr:false` is set because there will be no runtime server to run them on.
169
170#### Pre-rendering with a SPA Fallback
171
172If you want `ssr:false` but don't want to pre-render _all_ of your routes - that's fine too! You may have some paths where you need the performance/SEO benefits of pre-rendering, but other pages where a SPA would be fine.
173
174You can do this using the combination of config options as well - just limit your `prerender` config to the paths that you want to pre-render and React Router will also output a "SPA Fallback" HTML file that can be served to hydrate any other paths (using the same approach as [SPA Mode](./spa)).
175
176This will be written to one of the following paths:
177
178- `build/client/index.html` - If the `/` path is not pre-rendered
179- `build/client/__spa-fallback.html` - If the `/` path is pre-rendered
180
181```ts filename=react-router.config.ts
182import type { Config } from "@react-router/dev/config";
183
184export default {
185 ssr: false,
186
187 // SPA fallback will be written to build/client/index.html
188 prerender: ["/about-us"],
189
190 // SPA fallback will be written to build/client/__spa-fallback.html
191 prerender: ["/", "/about-us"],
192} satisfies Config;
193```
194
195You can configure your deployment server to serve this file for any path that otherwise would 404. Some hosts do this by default, but others don't. As an example, a host may support a `_redirects` file to do this:
196
197```
198# If you did not pre-render the `/` route
199/* /index.html 200
200
201# If you pre-rendered the `/` route
202/* /__spa-fallback.html 200
203```
204
205If you're getting 404s at valid routes for your app, it's likely you need to configure your host.
206
207Here's another example of how you can do this with the [`sirv-cli`](https://www.npmjs.com/package/sirv-cli#user-content-single-page-applications) tool:
208
209```sh
210# If you did not pre-render the `/` route
211sirv-cli build/client --single index.html
212
213# If you pre-rendered the `/` route
214sirv-cli build/client --single __spa-fallback.html
215```
216
217#### Invalid Exports
218
219When pre-rendering with `ssr:false`, React Router will error at build time if you have invalid exports to help prevent some mistakes that can be easily overlooked.
220
221- `headers`/`action` functions are prohibited in all routes because there will be no runtime server on which to run them
222- When using `ssr:false` without a `prerender` config (SPA Mode), a `loader` is permitted on the root route only
223- When using `ssr:false` with a `prerender` config, a `loader` is permitted on any route matched by a `prerender` path
224 - If you are using a `loader` on a pre-rendered route that has child routes, you will need to make sure the parent `loaderData` can be determined at run-time properly by either:
225 - Pre-rendering all child routes so that the parent `loader` can be called at build-time for each child route path and rendered into a `.data` file, or
226 - Use a `clientLoader` on the parent that can be called at run-time for non-pre-rendered child paths
227
228### Pre-rendering with API-only Mode (unstable)
229
230<docs-warning>API-only Mode is experimental and may change in minor or patch releases. It is not supported in RSC Framework Mode.</docs-warning>
231
232Use `ssr: "unstable_api-only"` with `prerender` to generate documents at build time while keeping a runtime server for loaders, actions, and route discovery:
233
234```ts filename=react-router.config.ts
235import type { Config } from "@react-router/dev/config";
236
237export default {
238 ssr: "unstable_api-only",
239 prerender: ["/"],
240} satisfies Config;
241```
242
243Document generation follows the same behavior as `ssr:false`: selected paths produce HTML and `.data` files, and other paths use a SPA fallback. The fallback is `__spa-fallback.html` when `/` is prerendered, or `index.html` otherwise.
244
245Prerendered pages hydrate using their build-time data. Pages using the fallback fetch server loader data during initialization. Server loaders and actions are available on all routes, including those outside the prerender list, and normal loader revalidation remains enabled.
246
247See [API-only Mode](../start/framework/rendering#api-only-mode-unstable) for deployment routing and configuring a separate API origin.