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

static-prerendering.md

206 lines8.6 KB

Static prerendering is the process of generating static HTML files for your application. This can be useful for either improving the performance of your application, as it allows you to serve pre-rendered HTML files to users without having to generate them on the fly or for deploying static sites to platforms that do not support server-side rendering.

Prerendering

TanStack Start can prerender your application to static HTML files, which can then be served to users without having to generate them on the fly. To prerender your application, you can add the prerender option to your tanstackStart configuration:

Vite

vite.config.ts
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    tanstackStart({
      prerender: {
        // Switch to true to enable prerendering
        enabled: false,

        // Disable if you need pages to be at `/page.html` instead of `/page/index.html`
        autoSubfolderIndex: true,

        // If disabled, only the root path or the paths defined in the pages config will be prerendered
        autoStaticPathsDiscovery: true,

        // How many prerender jobs to run at once
        concurrency: 14,

        // Whether to extract links from the HTML and prerender them also
        crawlLinks: true,

        // Filter function takes the page object and returns whether it should prerender
        filter: ({ path }) => !path.startsWith('/do-not-render-me'),

        // Number of times to retry a failed prerender job
        retryCount: 2,

        // Delay between retries in milliseconds
        retryDelay: 1000,

        // Maximum number of redirects to follow during prerendering
        maxRedirects: 5,

        // Maximum time in milliseconds to wait for each prerenderParams callback
        prerenderParamsTimeout: 30000,

        // Build route options used for prerendering separately from the server bundle
        separateRouteOptionsBundle: true,

        // Fail if an error occurs during prerendering
        failOnError: true,

        // Callback when page is successfully rendered
        onSuccess: ({ page }) => {
          console.log(`Rendered ${page.path}!`)
        },
      },
      // Optional configuration for specific pages
      // Note: When autoStaticPathsDiscovery is enabled (default), discovered static
      // routes will be merged with the pages specified below
      pages: [
        {
          path: '/my-page',
          prerender: { enabled: true, outputPath: '/my-page/index.html' },
        },
      ],
    }),
    viteReact(),
  ],
})

Rsbuild

rsbuild.config.ts
import { defineConfig } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'
import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'

export default defineConfig({
  plugins: [
    pluginReact(),
    tanstackStart({
      prerender: {
        // Switch to true to enable prerendering
        enabled: false,

        // Disable if you need pages to be at `/page.html` instead of `/page/index.html`
        autoSubfolderIndex: true,

        // If disabled, only the root path or the paths defined in the pages config will be prerendered
        autoStaticPathsDiscovery: true,

        // How many prerender jobs to run at once
        concurrency: 14,

        // Whether to extract links from the HTML and prerender them also
        crawlLinks: true,

        // Filter function takes the page object and returns whether it should prerender
        filter: ({ path }) => !path.startsWith('/do-not-render-me'),

        // Number of times to retry a failed prerender job
        retryCount: 2,

        // Delay between retries in milliseconds
        retryDelay: 1000,

        // Maximum number of redirects to follow during prerendering
        maxRedirects: 5,

        // Fail if an error occurs during prerendering
        failOnError: true,

        // Callback when page is successfully rendered
        onSuccess: ({ page }) => {
          console.log(`Rendered ${page.path}!`)
        },
      },
      // Optional configuration for specific pages
      // Note: When autoStaticPathsDiscovery is enabled (default), discovered static
      // routes will be merged with the pages specified below
      pages: [
        {
          path: '/my-page',
          prerender: { enabled: true, outputPath: '/my-page/index.html' },
        },
      ],
    }),
  ],
})

By default, Start builds route options used by prerenderParams and sitemap separately from the final server bundle so they can be used at build time without being deployed. Set prerender.separateRouteOptionsBundle to false if your deployment adapter does not support the extra build environment or if you prefer to keep those route options in the server bundle.

Automatic Static Route Discovery

All static paths will be automatically discovered and seamlessly merged with the specified pages config

Routes are excluded from automatic discovery in the following cases:

  • Routes with path parameters (e.g., /users/$userId) since they require specific parameter values
  • Layout routes (prefixed with _) since they don't render standalone pages
  • Routes without components (e.g., API routes)

Note: Dynamic routes can still be prerendered if they are linked from other pages when crawlLinks is enabled.

Dynamic Route Prerendering

Dynamic routes can declare prerenderParams to generate specific parameter values at build time. Each returned entry creates one page from the route path and can override sitemap or prerender options for that page.

// src/routes/posts/$postId.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/posts/$postId')({
  validateSearch: (search: Record<string, unknown>): { ref?: string } => ({
    ...(typeof search.ref === 'string' ? { ref: search.ref } : {}),
  }),
  sitemap: { changefreq: 'weekly' },
  prerender: { retryCount: 2, crawlLinks: false },
  prerenderParams: async () => {
    const posts = await fetchPosts()

    return posts.map((post) => ({
      params: { postId: post.id },
      search: { ref: 'sitemap' },
      sitemap: { lastmod: post.updatedAt, priority: 0.8 },
      prerender: { retryCount: 3 },
    }))
  },
  component: PostComponent,
})

function PostComponent() {
  const { postId } = Route.useParams()

  return <div>Post {postId}</div>
}

prerenderParams receives { routePath, signal }. The signal aborts when the build process is interrupted and when prerender.prerenderParamsTimeout elapses. Each entry's params and optional search values are typed from the route and used to create the generated URL. Search params are preserved in generated page paths and sitemap URLs using the router's default search serialization; custom stringifySearch router options are not applied during this build-time expansion.

Route-level prerender options provide defaults for entries returned by that route's prerenderParams. Each entry's prerender options override those defaults. In this example, generated pages use retryCount: 3 and retain crawlLinks: false. Explicit entries in the plugin's pages configuration take precedence when their paths match a generated page. Unspecified options fall back to the global prerender configuration.

Callbacks may return an array, a synchronous iterable, or an asynchronous iterable, directly or through a promise. Iterables are consumed as pages are queued, so an async generator can discover pages incrementally. Use the supplied signal to cancel pending data requests when discovery stops.

Code that is only referenced by prerenderParams or sitemap is removed from the client route bundle, so these options can import server-only data sources used to discover pages at build time.

Route-level sitemap metadata provides defaults for generated pages. Each entry's sitemap options override those defaults, and explicit plugin pages options take precedence over both. Static pages also receive defaults from their matching route. Use sitemap.exclude: true to generate HTML without adding the page to the sitemap. The route option does not enable sitemap output; configure the top-level sitemap option in your Start plugin.

When crawlLinks is enabled (default: true), TanStack Start will extract links from prerendered pages and prerender those linked pages as well.

For example, if / contains a link to /posts, then /posts will also be automatically prerendered.