feat(start): add prerender params and prune client-only server bundles #7346
main fromrefs/pull/7346/head·opened Summary#
Adds route-level prerenderParams support for TanStack Start, extends sitemap generation for dynamic routes, and removes statically SSR-disabled route code from server bundles.
Changes#
- Adds typed
prerenderParamsroute options for React, Solid, and Vue Start. - Supports synchronous, asynchronous, generator, and async-generator results.
- Passes each callback its route path and an abort signal.
- Generates prerender pages from returned path params and optional search params.
- Supports route-level and per-entry
prerenderandsitemapoptions. - Supports sitemap metadata including
priority,changefreq,lastmod, images, news, and alternate references. - Adds
prerender.prerenderParamsTimeout. - Adds
prerender.separateRouteOptionsBundle.
Bundle behavior#
- Removes
prerenderParamsandsitemapfrom client route bundles. - Uses a temporary route-options bundle during prerendering and removes it afterward.
- Removes prerender-only route options from final server output when separate route-options bundling is enabled.
- Removes statically unused
ssr: falsecomponents, loaders,beforeLoadhandlers, route pieces, and lazy route modules from server output. - Preserves required lazy route modules for
ssr: 'data-only'and dynamic SSR configurations. - Applies server-route pruning to Vite, Rsbuild, and React Server Components output.
- Supports Nitro v3 prerender builds with dynamic
prerenderParamspages and stripped route-option code. - Allows adapters to opt out of the separate route-options environment with
prerender.separateRouteOptionsBundle: false.
Coverage#
- React, Solid, and Vue Start.
- Vite and Rsbuild.
- React Server Components.
- Nitro v3.
- SSR, SPA, selective SSR, and prerender modes.
- Nested and pathless routes.
- Dynamic params, search params, encoded delimiters, and special characters.
- Dynamic sitemap entries and metadata.
- Client and server artifact checks for prerender-only and
ssr: falsecode. - Temporary route-options bundle cleanup.
Documentation#
- Adds React and Solid static prerendering documentation.
- Documents
prerenderParams, sitemap generation, timeout configuration, and separate route-options bundling.
Fixes #6400
Summary by CodeRabbit#
New Features
- Typed prerenderParams for dynamic build-time prerendering, per-entry sitemap/prerender controls, and per-entry search preservation.
- Sitemap enhancements: priority/changefreq/lastmod, image/news namespaces, and per-entry sitemap overrides.
- Config options: prerenderParamsTimeout and separateRouteOptionsBundle (default: enabled).
Documentation
- Updated static prerendering guides with dynamic route examples and deployment notes.
Tests
- Expanded e2e and unit tests covering prerenderParams, sitemap output, and client/server artifact validation.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsdocumentation
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-plugin-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-server-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: start-client-core
View your CI Pipeline Execution ↗ for commit b522781049af75019b9254aca549f2434fb85a92
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 11m 21s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 47s View ↗
☁️ Nx Cloud last updated this comment at
2026-07-20 04:28:30UTCMore templates
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-i18n-paraglide
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-router-react-example-basic-authjs
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-example-rscs
- tanstack-start-streaming-data-from-server-functions
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
- tanstack-router-vue-example-basic-jsx
- tanstack-router-vue-example-basic-file-based-jsx
- tanstack-router-vue-example-basic-file-based-sfc
- tanstack-router-solid-example-authenticated-routes
- tanstack-router-solid-example-authenticated-routes-firebase
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-default-search-params
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-basic-virtual-file-based
- tanstack-router-solid-example-basic-virtual-inside-file-based
- tanstack-router-solid-example-deferred-data
- tanstack-router-solid-i18n-paraglide
- tanstack-router-solid-example-kitchen-sink
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-kitchen-sink-solid-query
- tanstack-router-solid-example-kitchen-sink-solid-query-file-based
- tanstack-router-solid-example-large-file-based
- tanstack-router-solid-example-location-masking
- tanstack-router-solid-example-navigation-blocking
- tanstack-router-solid-example-quickstart
- tanstack-router-solid-example-quickstart-esbuild-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-router-solid-example-quickstart-rspack-file-based
- tanstack-router-solid-example-quickstart-webpack-file-based
- @tanstack/router-solid-mono-simple
- router-solid-mono-simple-lazy
- router-solid-monorepo-solid-query
- tanstack-router-solid-example-scroll-restoration
- tanstack-solid-router-search-validator-adapters
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-auth
- tanstack-solid-start-example-basic-authjs
- tanstack-solid-start-example-basic-cloudflare
- tanstack-solid-start-example-basic-netlify
- tanstack-solid-start-example-basic-nitro
- tanstack-start-example-basic-solid-query
- tanstack-solid-start-example-basic-static
- tanstack-solid-start-bun-hosting
- tanstack-solid-start-example-convex-better-auth
- tanstack-solid-start-example-counter
- tanstack-solid-start-i18n-paraglide
- tanstack-solid-start-example-large
- tanstack-solid-start-streaming-data-from-server-functions
- tanstack-solid-start-example-supabase-basic
- tanstack-solid-start-tailwind-v4
- tanstack-router-solid-example-view-transitions
- tanstack-router-solid-example-with-framer-motion
- tanstack-router-solid-example-with-trpc
@tanstack/arktype-adapter
npm i https://pkg.pr.new/@tanstack/arktype-adapter@7346@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@7346@tanstack/eslint-plugin-start
npm i https://pkg.pr.new/@tanstack/eslint-plugin-start@7346@tanstack/history
npm i https://pkg.pr.new/@tanstack/history@7346@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/@tanstack/nitro-v2-vite-plugin@7346@tanstack/react-router
npm i https://pkg.pr.new/@tanstack/react-router@7346@tanstack/react-router-devtools
npm i https://pkg.pr.new/@tanstack/react-router-devtools@7346@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@7346@tanstack/react-start
npm i https://pkg.pr.new/@tanstack/react-start@7346@tanstack/react-start-client
npm i https://pkg.pr.new/@tanstack/react-start-client@7346@tanstack/react-start-rsc
npm i https://pkg.pr.new/@tanstack/react-start-rsc@7346@tanstack/react-start-server
npm i https://pkg.pr.new/@tanstack/react-start-server@7346@tanstack/router-cli
npm i https://pkg.pr.new/@tanstack/router-cli@7346@tanstack/router-core
npm i https://pkg.pr.new/@tanstack/router-core@7346@tanstack/router-devtools
npm i https://pkg.pr.new/@tanstack/router-devtools@7346@tanstack/router-devtools-core
npm i https://pkg.pr.new/@tanstack/router-devtools-core@7346@tanstack/router-generator
npm i https://pkg.pr.new/@tanstack/router-generator@7346@tanstack/router-plugin
npm i https://pkg.pr.new/@tanstack/router-plugin@7346@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@7346@tanstack/router-utils
npm i https://pkg.pr.new/@tanstack/router-utils@7346@tanstack/router-vite-plugin
npm i https://pkg.pr.new/@tanstack/router-vite-plugin@7346@tanstack/solid-router
npm i https://pkg.pr.new/@tanstack/solid-router@7346@tanstack/solid-router-devtools
npm i https://pkg.pr.new/@tanstack/solid-router-devtools@7346@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@7346@tanstack/solid-start
npm i https://pkg.pr.new/@tanstack/solid-start@7346@tanstack/solid-start-client
npm i https://pkg.pr.new/@tanstack/solid-start-client@7346@tanstack/solid-start-server
npm i https://pkg.pr.new/@tanstack/solid-start-server@7346@tanstack/start-client-core
npm i https://pkg.pr.new/@tanstack/start-client-core@7346@tanstack/start-fn-stubs
npm i https://pkg.pr.new/@tanstack/start-fn-stubs@7346@tanstack/start-plugin-core
npm i https://pkg.pr.new/@tanstack/start-plugin-core@7346@tanstack/start-server-core
npm i https://pkg.pr.new/@tanstack/start-server-core@7346@tanstack/start-static-server-functions
npm i https://pkg.pr.new/@tanstack/start-static-server-functions@7346@tanstack/start-storage-context
npm i https://pkg.pr.new/@tanstack/start-storage-context@7346@tanstack/valibot-adapter
npm i https://pkg.pr.new/@tanstack/valibot-adapter@7346@tanstack/virtual-file-routes
npm i https://pkg.pr.new/@tanstack/virtual-file-routes@7346@tanstack/vue-router
npm i https://pkg.pr.new/@tanstack/vue-router@7346@tanstack/vue-router-devtools
npm i https://pkg.pr.new/@tanstack/vue-router-devtools@7346@tanstack/vue-router-ssr-query
npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@7346@tanstack/vue-start
npm i https://pkg.pr.new/@tanstack/vue-start@7346@tanstack/vue-start-client
npm i https://pkg.pr.new/@tanstack/vue-start-client@7346@tanstack/vue-start-server
npm i https://pkg.pr.new/@tanstack/vue-start-server@7346@tanstack/zod-adapter
npm i https://pkg.pr.new/@tanstack/zod-adapter@7346commit:
41c777eBundle Size Benchmarks#
- Commit:
ee96e25d1487 - Measured at:
2026-05-06T12:44:05.372Z - Baseline source:
history:35e88f04996d - Dashboard: bundle-size history
Scenario Current (gzip) Delta vs baseline Raw Brotli Trend react-router.minimal87.15 KiB 0 B (0.00%) 273.94 KiB 75.70 KiB ▅▅▅▅▅▅▅▅▅▅▅ react-router.full90.68 KiB 0 B (0.00%) 285.45 KiB 78.71 KiB ▅▅▅▅▅▅▅▅▅▅▅ solid-router.minimal35.38 KiB 0 B (0.00%) 106.25 KiB 31.81 KiB ▅▅▅▅▅▅▅▅▅▅▅ solid-router.full40.10 KiB 0 B (0.00%) 120.46 KiB 36.04 KiB ▅▅▅▅▅▅▅▅▅▅▅ vue-router.minimal53.15 KiB 0 B (0.00%) 151.39 KiB 47.73 KiB ▅▅▅▅▅▅▅▅▅▅▅ vue-router.full58.28 KiB 0 B (0.00%) 167.56 KiB 52.18 KiB ▅▅▅▅▅▅▅▅▅▅▅ react-start.minimal101.84 KiB 0 B (0.00%) 322.38 KiB 88.03 KiB ▁▁▁▁▁▁▁▁▁▁█ react-start.full105.27 KiB 0 B (0.00%) 332.71 KiB 91.00 KiB ▁▁▁▁▁▁▁▁▁▁█ react-start.rsbuild.minimal99.43 KiB 0 B (0.00%) 316.76 KiB 85.51 KiB ▁▁▁▁▁▁▁▁▁▁█ react-start.rsbuild.full102.72 KiB 0 B (0.00%) 327.19 KiB 88.31 KiB ▁▁▁▁▁▁▁▁▁▁█ solid-start.minimal49.48 KiB 0 B (0.00%) 152.36 KiB 43.69 KiB ▁▁▁▁▁▁▁▁▁▁█ solid-start.full55.27 KiB 0 B (0.00%) 169.27 KiB 48.60 KiB ▁▁▁▁▁▁▁▁▁▁█ Trend sparkline is historical gzip bytes ending with this PR measurement; lower is better.
- Commit:
Important
At least one additional CI pipeline execution has run since the conclusion below was written and it may no longer be applicable.
Nx Cloud is proposing a fix for your failed CI:#
We fix the
@tanstack/start-client-core:test:eslintfailure by reordering imports inhydrateStart.tsso that external, sibling, and type imports appear before the#tanstack-*virtual module imports, as required by theimport/orderrule. These pre-existing violations were hidden by the ESLint task cache and only surfaced when this PR's new files invalidated the cache for the package.Tip
✅ We verified this fix by re-running
@tanstack/start-client-core:test:eslint.diff --git a/packages/start-client-core/src/client/hydrateStart.ts b/packages/start-client-core/src/client/hydrateStart.ts index 206b7050..5ac46558 100644 --- a/packages/start-client-core/src/client/hydrateStart.ts +++ b/packages/start-client-core/src/client/hydrateStart.ts @@ -1,4 +1,7 @@ import { hydrate } from '@tanstack/router-core/ssr/client' +import { ServerFunctionSerializationAdapter } from './ServerFunctionSerializationAdapter' +import type { AnyRouter, AnySerializationAdapter } from '@tanstack/router-core' +import type { AnyStartInstanceOptions } from '../createStart' import { startInstance } from '#tanstack-start-entry' import { @@ -6,9 +9,6 @@ import { pluginSerializationAdapters, } from '#tanstack-start-plugin-adapters' import { getRouter } from '#tanstack-router-entry' -import { ServerFunctionSerializationAdapter } from './ServerFunctionSerializationAdapter' -import type { AnyRouter, AnySerializationAdapter } from '@tanstack/router-core' -import type { AnyStartInstanceOptions } from '../createStart' export async function hydrateStart(): Promise<AnyRouter> { const router = await getRouter()Because this branch comes from a fork, it is not possible for us to apply fixes directly, but you can apply the changes locally using the available options below.
Apply changes locally with:
Apply fix locally with your editor ↗ View interactive diff ↗npx nx-cloud apply-locally epUH-0jNj
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
e2e/vue-start/basic/rsbuild.config.ts (1)
8-37: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd
sitemapoption to rsbuild prerender config for feature parity with viteThe Vue
vite.config.tsconditionally enablessitemapgeneration whenisPrerenderis true, butrsbuild.config.tsomits this option. The prerendering test includes sitemap assertions, but usestest.skip()to gracefully skip the test if the sitemap is missing — so this won't cause a test failure. However, it creates an inconsistency where users building with rsbuild won't getsitemap.xmloutput during prerendering, unlike the vite build.🛠️ Proposed fix (mirror the vite config)
const prerenderConfiguration = { ... } export default defineConfig({ plugins: [ pluginBabel({ include: /\.(?:jsx|tsx)$/ }), pluginVue(), pluginVueJsx(), - tanstackStart({ - prerender: isPrerender ? prerenderConfiguration : undefined, - }), + tanstackStart({ + prerender: isPrerender ? prerenderConfiguration : undefined, + sitemap: isPrerender + ? { enabled: true, host: 'https://example.com' } + : undefined, + }), ],🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/vue-start/basic/rsbuild.config.ts` around lines 8 - 37, The rsbuild prerender config omits the sitemap option so rsbuild builds won't produce sitemap.xml; update the prerender configuration passed to tanstackStart in rsbuild.config.ts by adding sitemap: true when prerendering is enabled (e.g., extend prerenderConfiguration or the object passed to tanstackStart to include sitemap: true when isPrerender is true), referencing prerenderConfiguration, tanstackStart and isPrerender so the rsbuild prerender behavior matches the vite config.🧹 Nitpick comments (5)
e2e/solid-start/basic/rsbuild.config.ts (2)
7-23: 💤 Low valueDuplicate prerender filter list with
vite.config.ts— consider extracting a shared config helperThe
prerenderConfiguration(filter list +maxRedirects) defined here is byte-for-byte identical to theprerenderConfigurationine2e/solid-start/basic/vite.config.ts. The React e2e app already centralizes this ine2e/react-start/basic/start-mode-config.tsviagetStartModeConfig(). Applying the same pattern for Solid (and Vue) prevents silent filter-list drift when new routes are added.♻️ Proposed refactor — extract a shared start-mode-config.ts for Solid
Create
e2e/solid-start/basic/start-mode-config.ts:import { isPrerender } from './tests/utils/isPrerender' import { isSpaMode } from './tests/utils/isSpaMode' export function getStartModeConfig() { return { spa: isSpaMode ? { enabled: true, prerender: { outputPath: 'index.html' } } : undefined, prerender: isPrerender ? { enabled: true, filter: (page: { path: string }) => ![ '/this-route-does-not-exist', '/redirect', '/i-do-not-exist', '/not-found', '/specialChars/search', '/specialChars/hash', '/specialChars/malformed', '/search-params/default', '/transition', '/users', ].some((p) => page.path.includes(p)), maxRedirects: 100, } : undefined, sitemap: isPrerender ? { enabled: true, host: 'https://example.com' } : undefined, } }Then in both
vite.config.tsandrsbuild.config.ts:-import { isPrerender } from './tests/utils/isPrerender' +import { getStartModeConfig } from './start-mode-config' -const prerenderConfiguration = { ... } ... -tanstackStart({ prerender: isPrerender ? prerenderConfiguration : undefined, sitemap: ... }) +tanstackStart(getStartModeConfig())🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/solid-start/basic/rsbuild.config.ts` around lines 7 - 23, The prerenderConfiguration object (including filter and maxRedirects) is duplicated; extract it into a shared getStartModeConfig() helper (like the React approach) that returns the prerender config (with enabled, filter function, maxRedirects and sitemap/spa variants) and import that helper into both vite.config.ts and rsbuild.config.ts, then replace the local prerenderConfiguration constant with the shared value (referencing getStartModeConfig and its prerender property) so both build configs use the same filter array and settings.
7-35: ⚡ Quick winsitemapoption missing from rsbuild prerender config — feature parity gape2e/solid-start/basic/vite.config.tsincludessitemap: { enabled: true, host: 'https://example.com' }whenisPrerenderis true, but the rsbuild config does not. While the sitemap test inprerendering.spec.ts(line 147) includes atest.skip()guard that gracefully skips when the sitemap is disabled, the inconsistency means the rsbuild build lacks this feature compared to vite. Consider adding the sitemap option for parity:Optional enhancement
tanstackStart({ prerender: isPrerender ? prerenderConfiguration : undefined, + sitemap: isPrerender + ? { enabled: true, host: 'https://example.com' } + : undefined, }),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/solid-start/basic/rsbuild.config.ts` around lines 7 - 35, The rsbuild config is missing the sitemap option for prerender parity; update the tanstackStart call in rsbuild.config.ts (where tanstackStart({ prerender: isPrerender ? prerenderConfiguration : undefined })) so that when isPrerender is true the prerender config includes sitemap: { enabled: true, host: 'https://example.com' } (either by adding sitemap to the existing prerenderConfiguration object or by merging it when passing into tanstackStart).packages/start-client-core/src/prerenderParams.ts (1)
61-90: ⚡ Quick winDocument expected date string formats.
lastmodandnews.publicationDateacceptstring | Date, but the sitemap writer normalizes toYYYY-MM-DD(perbuild-sitemap.test.ts). Adding short JSDoc on these fields (e.g., "ISO 8601 date orYYYY-MM-DD;Dateis formatted to W3C date format") would prevent users from passing arbitrary strings that get emitted verbatim into the XML.📝 Proposed JSDoc additions
alternateRefs?: Array<{ href: string hreflang: string }> + /** + * Last modification date. Accepts a `Date` (formatted as `YYYY-MM-DD`) + * or a W3C/ISO 8601 date string. Strings are emitted verbatim, so + * pass `YYYY-MM-DD` or full ISO 8601 to remain spec-compliant. + */ lastmod?: string | Date ... news?: { publication: { name: string language: string } + /** + * Publication date. `Date` is formatted as `YYYY-MM-DD`; + * strings should be W3C/ISO 8601 to remain spec-compliant. + */ publicationDate: string | Date title: string }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/prerenderParams.ts` around lines 61 - 90, Update the RouteSitemapOptions interface JSDoc to document expected date string formats for lastmod and news.publicationDate: add brief comments on the lastmod property and the nested news.publicationDate explaining they accept ISO 8601 strings or YYYY-MM-DD and that Date values will be formatted to W3C/ISO (normalized to YYYY-MM-DD by the sitemap writer). Reference the RouteSitemapOptions interface and its lastmod and news.publicationDate fields so consumers know strings will be emitted verbatim unless they follow the documented formats.packages/start-plugin-core/tests/prerender-routes-plugin.test.ts (1)
39-69: 💤 Low valueLGTM – consider adding a
TSS_PRERENDER_DYNAMIC_ROUTESassertion to test 2.Test 2 verifies that
/posts/$slug(which hascomponentbut notprerenderParams) stays out ofTSS_PRERENDABLE_PATHS, but doesn't confirm it's also absent fromTSS_PRERENDER_DYNAMIC_ROUTES. Test 3 covers this indirectly, so it's not a bug — just a small coverage gap.✨ Optional assertion to make test 2 self-contained
expect(globalThis.TSS_PRERENDABLE_PATHS).toEqual([{ path: '/' }]) + expect(globalThis.TSS_PRERENDER_DYNAMIC_ROUTES).toEqual([]) })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/prerender-routes-plugin.test.ts` around lines 39 - 69, Add an assertion in the test "does not store API, layout, or dynamic routes as static paths" to also verify that dynamic routes without prerenderParams are not recorded in TSS_PRERENDER_DYNAMIC_ROUTES: after invoking plugin.onRouteTreeChanged (using prerenderRoutesPlugin and the route node with routePath '/posts/$slug'), assert that globalThis.TSS_PRERENDER_DYNAMIC_ROUTES does not contain an entry for '/posts/$slug' (or is empty), so the test checks both TSS_PRERENDABLE_PATHS and globalThis.TSS_PRERENDER_DYNAMIC_ROUTES consistency.packages/start-plugin-core/src/vite/prerender.ts (1)
38-50: ⚡ Quick winAddress the fragile output filename assumption.
The code computes the server output filename as
${basename(serverInput, extname(serverInput))}.js, which assumes the built file uses the same base name as the input and always ends in.js. A project that setsrollupOptions.output.entryFileNameswith a hash pattern or emits.cjs/.mjswould produce anERR_MODULE_NOT_FOUNDcrash at prerender time. Consider reading from a Vite manifest or build metadata to get the actual output filename instead of computing it.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/vite/prerender.ts` around lines 38 - 50, The code that builds serverEntryPath from serverInput (using basename + ".js") is fragile for hashed or non-.js outputs; instead look up the actual built entry filename from the Vite/Rollup manifest or build output metadata and use that to form serverEntryPath. Concretely: when preparing to import the built server entry, read the build manifest (or Rollup output info) in the same output directory returned by getServerOutputDirectory(serverEnv.config), find the entry whose source or file corresponds to serverInput (use serverInput as the original input key), and use the manifest-provided filename (which may be .cjs/.mjs or hashed) for import; update the logic around serverInput, serverOutputDir, serverEntryPath and the await import(...) to use the manifest-resolved filename instead of `${basename(...)}.js`.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@e2e/vue-start/basic/tests/prerendering.spec.ts`: - Line 119: The assertion expect(html).toContain('2') is too broad; update the test to assert the specific element or text that indicates the search param page=2 was rendered instead of any occurrence of the character '2'. Replace the loose expect(html).toContain('2') check (referencing the html variable and the expect call) with a targeted assertion—either assert the exact HTML substring for the element that should show "2" (e.g., the specific heading or pager markup) or parse html with a DOM parser (e.g., JSDOM) and use querySelector to assert the element's textContent equals '2' (or matches a precise regex like /\bpage[:\s]*2\b/). In `@packages/start-plugin-core/src/prerender-params-runner.ts`: - Around line 131-142: The promise executor currently checks signal.aborted once but then schedules callback via Promise.resolve().then(callback) allowing a race; change the scheduled invocation to first re-check signal.aborted and throw/reject if set before calling callback (e.g. replace .then(callback) with .then(() => { if (signal.aborted) throw signal.reason ?? new Error('prerenderParams aborted'); return callback(); })) and ensure the abort listener (abort) is removed/cleanup occurs after resolve/reject so the handler and callback cannot both run; reference the Promise executor, signal, callback, and abort variables in prerender-params-runner.ts. --- Outside diff comments: In `@e2e/vue-start/basic/rsbuild.config.ts`: - Around line 8-37: The rsbuild prerender config omits the sitemap option so rsbuild builds won't produce sitemap.xml; update the prerender configuration passed to tanstackStart in rsbuild.config.ts by adding sitemap: true when prerendering is enabled (e.g., extend prerenderConfiguration or the object passed to tanstackStart to include sitemap: true when isPrerender is true), referencing prerenderConfiguration, tanstackStart and isPrerender so the rsbuild prerender behavior matches the vite config. --- Nitpick comments: In `@e2e/solid-start/basic/rsbuild.config.ts`: - Around line 7-23: The prerenderConfiguration object (including filter and maxRedirects) is duplicated; extract it into a shared getStartModeConfig() helper (like the React approach) that returns the prerender config (with enabled, filter function, maxRedirects and sitemap/spa variants) and import that helper into both vite.config.ts and rsbuild.config.ts, then replace the local prerenderConfiguration constant with the shared value (referencing getStartModeConfig and its prerender property) so both build configs use the same filter array and settings. - Around line 7-35: The rsbuild config is missing the sitemap option for prerender parity; update the tanstackStart call in rsbuild.config.ts (where tanstackStart({ prerender: isPrerender ? prerenderConfiguration : undefined })) so that when isPrerender is true the prerender config includes sitemap: { enabled: true, host: 'https://example.com' } (either by adding sitemap to the existing prerenderConfiguration object or by merging it when passing into tanstackStart). In `@packages/start-client-core/src/prerenderParams.ts`: - Around line 61-90: Update the RouteSitemapOptions interface JSDoc to document expected date string formats for lastmod and news.publicationDate: add brief comments on the lastmod property and the nested news.publicationDate explaining they accept ISO 8601 strings or YYYY-MM-DD and that Date values will be formatted to W3C/ISO (normalized to YYYY-MM-DD by the sitemap writer). Reference the RouteSitemapOptions interface and its lastmod and news.publicationDate fields so consumers know strings will be emitted verbatim unless they follow the documented formats. In `@packages/start-plugin-core/src/vite/prerender.ts`: - Around line 38-50: The code that builds serverEntryPath from serverInput (using basename + ".js") is fragile for hashed or non-.js outputs; instead look up the actual built entry filename from the Vite/Rollup manifest or build output metadata and use that to form serverEntryPath. Concretely: when preparing to import the built server entry, read the build manifest (or Rollup output info) in the same output directory returned by getServerOutputDirectory(serverEnv.config), find the entry whose source or file corresponds to serverInput (use serverInput as the original input key), and use the manifest-provided filename (which may be .cjs/.mjs or hashed) for import; update the logic around serverInput, serverOutputDir, serverEntryPath and the await import(...) to use the manifest-resolved filename instead of `${basename(...)}.js`. In `@packages/start-plugin-core/tests/prerender-routes-plugin.test.ts`: - Around line 39-69: Add an assertion in the test "does not store API, layout, or dynamic routes as static paths" to also verify that dynamic routes without prerenderParams are not recorded in TSS_PRERENDER_DYNAMIC_ROUTES: after invoking plugin.onRouteTreeChanged (using prerenderRoutesPlugin and the route node with routePath '/posts/$slug'), assert that globalThis.TSS_PRERENDER_DYNAMIC_ROUTES does not contain an entry for '/posts/$slug' (or is empty), so the test checks both TSS_PRERENDABLE_PATHS and globalThis.TSS_PRERENDER_DYNAMIC_ROUTES consistency.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
b58420f7-00a8-4fa8-b77b-ab44168b7d58📥 Commits
Reviewing files that changed from the base of the PR and between bcefc84d7e83fc4fd97e75ee4b95a7726f17f1f0 and cb7a05dd953af4a4e18bbdb9cee13159ebac06f8.
📒 Files selected for processing (48)
.changeset/tall-trees-prerender-params.mddocs/start/framework/react/guide/static-prerendering.mddocs/start/framework/solid/guide/static-prerendering.mde2e/react-start/basic/src/routeTree.gen.tse2e/react-start/basic/src/routes/-prerender-params.server.tse2e/react-start/basic/src/routes/_layout/_layout-2/prerender-nested.$slug.tsxe2e/react-start/basic/src/routes/prerender-params.$slug.tsxe2e/react-start/basic/start-mode-config.tse2e/react-start/basic/tests/prerendering.spec.tse2e/solid-start/basic/package.jsone2e/solid-start/basic/rsbuild.config.tse2e/solid-start/basic/src/routeTree.gen.tse2e/solid-start/basic/src/routes/-prerender-params.server.tse2e/solid-start/basic/src/routes/_layout/_layout-2/prerender-nested.$slug.tsxe2e/solid-start/basic/src/routes/prerender-params.$slug.tsxe2e/solid-start/basic/tests/prerendering.spec.tse2e/solid-start/basic/vite.config.tse2e/vue-start/basic/package.jsone2e/vue-start/basic/rsbuild.config.tse2e/vue-start/basic/src/routeTree.gen.tse2e/vue-start/basic/src/routes/-prerender-params.server.tse2e/vue-start/basic/src/routes/_layout/_layout-2/prerender-nested.$slug.tsxe2e/vue-start/basic/src/routes/prerender-params.$slug.tsxe2e/vue-start/basic/tests/prerendering.spec.tse2e/vue-start/basic/vite.config.tspackages/start-client-core/src/index.tsxpackages/start-client-core/src/prerenderParams.tspackages/start-client-core/src/tests/prerenderParams.test-d.tspackages/start-plugin-core/src/build-sitemap.tspackages/start-plugin-core/src/global.d.tspackages/start-plugin-core/src/post-build.tspackages/start-plugin-core/src/prerender-params-runner.tspackages/start-plugin-core/src/prerender-route-options.tspackages/start-plugin-core/src/prerender.tspackages/start-plugin-core/src/rsbuild/post-build.tspackages/start-plugin-core/src/rsbuild/start-router-plugin.tspackages/start-plugin-core/src/schema.tspackages/start-plugin-core/src/start-router-plugin/constants.tspackages/start-plugin-core/src/start-router-plugin/generator-plugins/prerender-routes-plugin.tspackages/start-plugin-core/src/vite/prerender.tspackages/start-plugin-core/src/vite/start-router-plugin/plugin.tspackages/start-plugin-core/tests/build-sitemap.test.tspackages/start-plugin-core/tests/prerender-params-runner.test.tspackages/start-plugin-core/tests/prerender-routes-plugin.test.tspackages/start-plugin-core/tests/prerender-ssrf.test.tspackages/start-plugin-core/tests/start-router-plugin-constants.test.tspackages/start-server-core/src/createStartHandler.tspackages/start-server-core/src/global.d.ts
e2e/vue-start/basic/tests/prerendering.spec.ts line 119OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -46,0 +99,21 @@99+ distDir,100+ 'prerender-params/reserved%3Fhash%23plus%2B/index.html',101+ )102+103+ expect(existsSync(htmlPath)).toBe(true)104+105+ const html = readFileSync(htmlPath, 'utf-8')106+ expect(html).toContain('Prerendered slug:')107+ expect(html).toContain('reserved?hash#plus+')108+ })109+110+ test('should preserve route prerenderParams search params', () => {111+ const htmlPath = join(distDir, 'prerender-params/with-query/index.html')112+113+ expect(existsSync(htmlPath)).toBe(true)114+115+ const html = readFileSync(htmlPath, 'utf-8')116+ expect(html).toContain('Prerendered slug:')117+ expect(html).toContain('with-query')118+ expect(html).toContain('Search page:')119+ expect(html).toContain('2')⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Overly broad string assertion may produce false passes.
expect(html).toContain('2')will match any occurrence of the character'2'in the rendered HTML (e.g. in<h2>, script/style content, or other numeric data), making the assertion unreliable as a signal that the search parampage: 2was actually rendered.🛡️ Proposed fix – narrow the assertion
- expect(html).toContain('2') + expect(html).toContain('Search page: 2')📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change119- expect(html).toContain('2')119+ expect(html).toContain('Search page: 2')🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/vue-start/basic/tests/prerendering.spec.ts` at line 119, The assertion expect(html).toContain('2') is too broad; update the test to assert the specific element or text that indicates the search param page=2 was rendered instead of any occurrence of the character '2'. Replace the loose expect(html).toContain('2') check (referencing the html variable and the expect call) with a targeted assertion—either assert the exact HTML substring for the element that should show "2" (e.g., the specific heading or pager markup) or parse html with a DOM parser (e.g., JSDOM) and use querySelector to assert the element's textContent equals '2' (or matches a precise regex like /\bpage[:\s]*2\b/).✅ Addressed in commit 7990d41
packages/start-plugin-core/src/prerender-params-runner.ts lines 131 to 142OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +122,21 @@122+ }, timeout)123+124+ return () => clearTimeout(timeoutId)125+}126+127+async function call<T>(128+ callback: () => T | Promise<T>,129+ signal: AbortSignal,130+): Promise<T> {131+ if (signal.aborted) {132+ throw signal.reason ?? new Error('prerenderParams aborted')133+ }134+135+ return await new Promise<T>((resolve, reject) => {136+ const abort = () =>137+ reject(signal.reason ?? new Error('prerenderParams aborted'))138+ signal.addEventListener('abort', abort, { once: true })139+140+ Promise.resolve()141+ .then(callback)142+ .then(resolve, reject)⚠️ Potential issue | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
In the AbortController/AbortSignal API, if a signal is already aborted, does adding an 'abort' event listener fire that listener automatically, or only on future abort events?💡 Result:
If an AbortSignal is already aborted when you call signal.addEventListener('abort', listener), the listener will be invoked (i.e., it does not wait for a future abort event). This is why MDN examples and guidance commonly check signal.aborted / call signal.throwIfAborted to handle the “already aborted” case immediately, and why an already-aborted signal still has abort handling semantics available immediately rather than only later [1][2]. A subtle but important nuance: AbortSignal.abort (the static method) returns an already-aborted signal “which does not trigger an abort event,” so in that specific case you should not expect the 'abort' event listener to run [3]. In contrast, when the signal becomes aborted via AbortController.abort, the abort event is fired [4]. Practical recommendation: if you’re writing abortable code, handle both cases by checking signal.aborted (or using signal.throwIfAborted) in addition to attaching the 'abort' listener, since some signals/creation paths may behave differently with respect to firing the event [1][2].
Citations:
- 1: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
- 2: https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted
- 3: https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static
- 4: https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event
🏁 Script executed:
cd packages/start-plugin-core && wc -l src/prerender-params-runner.tsRepository: TanStack/router
Length of output: 94
🏁 Script executed:
cd packages/start-plugin-core && cat -n src/prerender-params-runner.ts | sed -n '120,155p'Repository: TanStack/router
Length of output: 1205
🏁 Script executed:
cd packages/start-plugin-core && grep -n "call(" src/prerender-params-runner.ts | head -20Repository: TanStack/router
Length of output: 96
🏁 Script executed:
cd packages/start-plugin-core && sed -n '127,147p' src/prerender-params-runner.tsRepository: TanStack/router
Length of output: 618
Abort race can still run callback after cancellation
callcheckssignal.abortedonce, then schedulescallback. If abort happens between that check and callback execution, the callback queued as a microtask can still execute despite the abort firing. Re-checksignal.abortedimmediately before invokingcallbackto enforce cancellation deterministically.Suggested fix
async function call<T>( callback: () => T | Promise<T>, signal: AbortSignal, ): Promise<T> { if (signal.aborted) { throw signal.reason ?? new Error('prerenderParams aborted') } return await new Promise<T>((resolve, reject) => { const abort = () => reject(signal.reason ?? new Error('prerenderParams aborted')) signal.addEventListener('abort', abort, { once: true }) Promise.resolve() - .then(callback) + .then(() => { + if (signal.aborted) { + throw signal.reason ?? new Error('prerenderParams aborted') + } + return callback() + }) .then(resolve, reject) .finally(() => { signal.removeEventListener('abort', abort) }) }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 131 - 142, The promise executor currently checks signal.aborted once but then schedules callback via Promise.resolve().then(callback) allowing a race; change the scheduled invocation to first re-check signal.aborted and throw/reject if set before calling callback (e.g. replace .then(callback) with .then(() => { if (signal.aborted) throw signal.reason ?? new Error('prerenderParams aborted'); return callback(); })) and ensure the abort listener (abort) is removed/cleanup occurs after resolve/reject so the handler and callback cannot both run; reference the Promise executor, signal, callback, and abort variables in prerender-params-runner.ts.✅ Addressed in commit 7990d41
Merging this PR will regress 1 benchmark#
:warning: Different runtime environments detected
Some benchmarks with significant performance changes were compared across different runtime environments, which may affect the accuracy of the results.
⚡ 6improved benchmarks❌ 1regressed benchmark✅ 173untouched benchmarksWarning
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes#
Mode Benchmark BASEHEADEfficiency ❌ Memory mem server server-fn-churn (solid)263 KB 274 KB -4% ⚡ Memory mem server error-paths redirect (vue)979.9 KB 306.5 KB ×3.2 ⚡ Memory mem server peak-large-page (react)2,216.6 KB 954.5 KB ×2.3 ⚡ Memory mem server error-paths unmatched (react)567.3 KB 269.6 KB ×2.1 ⚡ Memory mem server error-paths not-found (solid)1,146.2 KB 780.4 KB +46.86% ⚡ Memory mem server serialization-payload (react)5 MB 3.4 MB +44.77% ⚡ Memory mem server streaming-peak chunked (vue)12.1 MB 11.1 MB +8.87% Tip
Investigate this regression by commenting
@codspeedbot fix this regressionon this PR, or directly use the CodSpeed MCP with your agent.
Comparingnikuscs:feat-server-side-params(41c777e) withmain(edf5575)🧹 Nitpick comments (2)
packages/start-plugin-core/src/prerender-params-runner.ts (2)
68-89: 💤 Low valueDefensive validation for non-iterable
entries.for (const entry of entries)will throw a non-descriptiveTypeError: entries is not iterableif a user-authoredprerenderParamsmistakenly returnsundefined/nullor a non-array. A small guard with a clearer error message attributing the offending route improves DX without changing the happy path.♻️ Suggested guard
const entries = await call( () => options.prerenderParams!({ routePath: route.routePath, signal: controller.signal, }), controller.signal, ).finally(cleanupTimeout) + if (!Array.isArray(entries)) { + throw new Error( + `prerenderParams for route ${route.routePath} must return an array; got ${typeof entries}`, + ) + } + for (const entry of entries) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 68 - 89, The loop assumes the result of calling options.prerenderParams via call(...) is iterable; add a defensive validation after the await that checks entries is an array (or at least iterable) and throw a clear Error that includes route.routePath (or skip non-iterable with a logged warning) so users get a descriptive message instead of "entries is not iterable"; update the block around the awaited call in prerender-params-runner.ts (where entries is assigned from call(...), which uses controller.signal and options.prerenderParams) to validate entries before the for (const entry of entries) loop and only proceed to call create(...), filter, pagesByPath.set(...), and merge(...) when entries is valid.
155-186: 💤 Low valueRoute-level
options.prerenderis silently dropped on generated pages.create()mergesoptions.sitemapwithentry.sitemapbut assignsprerender: entry.prerenderdirectly, ignoringoptions.prerenderentirely. If a route declaresprerender: { headers: { … } }at the route level and an entry omitsprerender, those headers are lost on the generated page even though the analogous sitemap config is preserved. If this asymmetry is intentional (e.g., prerender options are applied later in the pipeline), a brief comment would help; otherwise consider symmetric merging.♻️ Symmetric merge sketch
return { path: interpolatedPath + search(entry.search), sitemap: sitemap(options.sitemap, entry.sitemap), - prerender: entry.prerender, + prerender: prerender(options.prerender, entry.prerender), }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 155 - 186, The create function currently drops route-level prerender options by returning prerender: entry.prerender instead of merging with options.prerender; update create (in prerender-params-runner.ts) to merge options.prerender with entry.prerender (similar to how sitemap(options.sitemap, entry.sitemap) is merged) so route-level defaults (e.g., headers) are preserved when entry.prerender is absent—either call an existing merge helper or shallow/deep-merge options.prerender and entry.prerender and return the merged result under prerender.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/start-plugin-core/src/prerender-params-runner.ts`: - Around line 68-89: The loop assumes the result of calling options.prerenderParams via call(...) is iterable; add a defensive validation after the await that checks entries is an array (or at least iterable) and throw a clear Error that includes route.routePath (or skip non-iterable with a logged warning) so users get a descriptive message instead of "entries is not iterable"; update the block around the awaited call in prerender-params-runner.ts (where entries is assigned from call(...), which uses controller.signal and options.prerenderParams) to validate entries before the for (const entry of entries) loop and only proceed to call create(...), filter, pagesByPath.set(...), and merge(...) when entries is valid. - Around line 155-186: The create function currently drops route-level prerender options by returning prerender: entry.prerender instead of merging with options.prerender; update create (in prerender-params-runner.ts) to merge options.prerender with entry.prerender (similar to how sitemap(options.sitemap, entry.sitemap) is merged) so route-level defaults (e.g., headers) are preserved when entry.prerender is absent—either call an existing merge helper or shallow/deep-merge options.prerender and entry.prerender and return the merged result under prerender.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e8757849-427a-4490-af73-adf1d0583e55📥 Commits
Reviewing files that changed from the base of the PR and between cb7a05dd953af4a4e18bbdb9cee13159ebac06f8 and 7990d411cf9614bf25f14a4f03a5667a174fbf13.
📒 Files selected for processing (6)
e2e/react-start/basic/tests/prerendering.spec.tse2e/solid-start/basic/tests/prerendering.spec.tse2e/vue-start/basic/tests/prerendering.spec.tspackages/start-plugin-core/src/post-build.tspackages/start-plugin-core/src/prerender-params-runner.tspackages/start-plugin-core/tests/post-server-build.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- e2e/react-start/basic/tests/prerendering.spec.ts
- e2e/solid-start/basic/tests/prerendering.spec.ts
- e2e/vue-start/basic/tests/prerendering.spec.ts
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/start-plugin-core/src/post-build.ts (1)
17-18: 💤 Low valuespaOnlyis inferred asboolean | undefinedrather thanbooleanWhen
startConfig.spaisundefined, the?.enabledshort-circuits the&&toundefined(notfalse). All current usages (if (spaOnly), ternary) treat it as a falsy check, so there's no runtime defect, but the inferred typeboolean | undefinedis weaker than needed under strict mode.♻️ Suggested refinement
- const spaOnly = - startConfig.spa?.enabled && startConfig.prerender?.enabled !== true + const spaOnly = + !!startConfig.spa?.enabled && startConfig.prerender?.enabled !== true🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/post-build.ts` around lines 17 - 18, The variable spaOnly is inferred as boolean | undefined because startConfig.spa?.enabled can short-circuit to undefined; coerce the result to a true boolean so its type is boolean (e.g., wrap the whole expression with a boolean coercion such as Boolean(...) or double-negation) and keep the same logical check using startConfig.spa?.enabled and startConfig.prerender?.enabled !== true so usages like if (spaOnly) remain unchanged.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/start-plugin-core/tests/post-server-build.test.ts`: - Around line 14-41: The test is misleading because postBuild does not read globalThis.TSS_PRERENDER_DYNAMIC_ROUTES; remove the global setup and adjust the test to assert the actual condition under test by deleting the globalThis.TSS_PRERENDER_DYNAMIC_ROUTES assignment (and its cleanup) and rename the it(...) description to something like "does not enable prerendering when pages array is empty and prerender config is absent" while keeping the same call to postBuild, the mocked adapter.prerender and the expectation that prerender was not called; alternatively move this scenario into an integration test that invokes the real prerender implementation if you intend to assert behavior around TSS_PRERENDER_DYNAMIC_ROUTES. --- Nitpick comments: In `@packages/start-plugin-core/src/post-build.ts`: - Around line 17-18: The variable spaOnly is inferred as boolean | undefined because startConfig.spa?.enabled can short-circuit to undefined; coerce the result to a true boolean so its type is boolean (e.g., wrap the whole expression with a boolean coercion such as Boolean(...) or double-negation) and keep the same logical check using startConfig.spa?.enabled and startConfig.prerender?.enabled !== true so usages like if (spaOnly) remain unchanged.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
3acc396d-cd42-4fb7-9e36-8cac7d3d593d📥 Commits
Reviewing files that changed from the base of the PR and between 7990d411cf9614bf25f14a4f03a5667a174fbf13 and 6f5afd7b7a8368ed3f39a90233e303167829a096.
📒 Files selected for processing (4)
packages/start-plugin-core/src/post-build.tspackages/start-plugin-core/src/prerender.tspackages/start-plugin-core/src/vite/prerender.tspackages/start-plugin-core/tests/post-server-build.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/start-plugin-core/src/vite/prerender.ts
- packages/start-plugin-core/src/prerender.ts
packages/start-plugin-core/tests/post-server-build.test.ts lines 14 to 41OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -13,0 +21,21 @@21+22+ try {23+ await postBuild({24+ startConfig: {25+ pages: [],26+ router: { basepath: '' },27+ serverFns: { base: '' },28+ spa: { enabled: false },29+ sitemap: { enabled: false },30+ } as any,31+ adapter: {32+ getClientOutputDirectory: () => '/client',33+ prerender,34+ },35+ })36+ } finally {37+ globalThis.TSS_PRERENDER_DYNAMIC_ROUTES = undefined38+ }39+40+ expect(prerender).not.toHaveBeenCalled()41+ })⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Verify where TSS_PRERENDER_DYNAMIC_ROUTES is referenced # to confirm whether post-build.ts or its direct call chain reads it. rg -n 'TSS_PRERENDER_DYNAMIC_ROUTES' --type ts -C 3Repository: TanStack/router
Length of output: 4950
Move the misleading global setup or rename the test to reflect the actual mechanism being tested
The test sets
globalThis.TSS_PRERENDER_DYNAMIC_ROUTES(lines 18–20) butpost-build.tsnever reads this global. The test passes solely becausestartConfig.pagesis empty and noprerenderconfig is provided—not because post-build has any guard against the dynamic routes global.This creates false confidence that the code defends against
TSS_PRERENDER_DYNAMIC_ROUTES. Since the adapterprerenderis mocked,prerender.ts(where the global is actually consumed) is never invoked, so the test cannot verify the claimed behavior.Either:
- Remove the global assignment and rename the test to reflect the true mechanism: "does not enable prerendering when pages array is empty and prerender config is absent"
- Move this contract to an integration test that invokes the actual prerender implementation
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/post-server-build.test.ts` around lines 14 - 41, The test is misleading because postBuild does not read globalThis.TSS_PRERENDER_DYNAMIC_ROUTES; remove the global setup and adjust the test to assert the actual condition under test by deleting the globalThis.TSS_PRERENDER_DYNAMIC_ROUTES assignment (and its cleanup) and rename the it(...) description to something like "does not enable prerendering when pages array is empty and prerender config is absent" while keeping the same call to postBuild, the mocked adapter.prerender and the expectation that prerender was not called; alternatively move this scenario into an integration test that invokes the real prerender implementation if you intend to assert behavior around TSS_PRERENDER_DYNAMIC_ROUTES.Nx Cloud has identified a flaky task in your failed CI:#
Since the failure was identified as flaky, the solution is to rerun CI. Because this branch comes from a fork, it is not possible for us to push directly, but you can rerun by pushing an empty commit:
git commit --allow-empty -m "chore: trigger rerun" git push View detailed reasoning in Nx Cloud ↗
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Important
At least one additional CI pipeline execution has run since the conclusion below was written and it may no longer be applicable.
Nx Cloud is proposing a fix for your failed CI:#
We externalize
cloudflare:*modules in the prerender environment's rollup/rolldown build config to fix the Cloudflare e2e build failures. The new separate prerender Vite environment is a plain Node.js context that lacks the Cloudflare plugin's module resolution, causing Rolldown to fail when it encountersimport { env } from 'cloudflare:workers'insidestatic.tsx?tss-serverfn-split. Since the split module is only referenced via a lazy dynamicimport()in the server function resolver manifest and is never invoked during prerender router initialization, markingcloudflare:*as external is safe and sufficient to unblock the build.Tip
✅ We verified this fix by re-running
tanstack-react-start-e2e-basic-cloudflare:build,tanstack-vue-start-e2e-basic-cloudflare:build,tanstack-solid-start-e2e-basic-cloudflare:buildand 3 more.Suggested Fix changes
diff --git a/packages/start-plugin-core/src/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts index 06ac6eae..09bd070f 100644 --- a/packages/start-plugin-core/src/vite/planning.ts +++ b/packages/start-plugin-core/src/vite/planning.ts @@ -106,11 +106,8 @@ export function createViteConfigPlan(opts: { consumer: 'server', build: { ssr: true, - ...buildViteInputOptions(prerenderInput), - outDir: join( - opts.serverOutputDirectory, - '.tanstack/prerender', - ), + ...buildViteInputOptions(prerenderInput, [/^cloudflare:/]), + outDir: join(opts.serverOutputDirectory, '.tanstack/prerender'), commonjsOptions: { include: [/node_modules/], }, @@ -249,8 +246,11 @@ function escapeEntries(entries: Array<string>) { return entries.map((entry) => escapePath(entry)) } -function buildViteInputOptions(input: NonNullable<vite.BuildOptions['rollupOptions']>['input']) { - const bundlerOptions = { input } +function buildViteInputOptions( + input: NonNullable<vite.BuildOptions['rollupOptions']>['input'], + external?: NonNullable<vite.BuildOptions['rollupOptions']>['external'], +) { + const bundlerOptions = external ? { input, external } : { input } return { rollupOptions: bundlerOptions,Because this branch comes from a fork, it is not possible for us to apply fixes directly, but you can apply the changes locally using the available options below.
Apply changes locally with:
Apply fix locally with your editor ↗ View interactive diff ↗npx nx-cloud apply-locally 3Nq5-AgS3
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Nx Cloud has identified a flaky task in your failed CI:#
Since the failure was identified as flaky, the solution is to rerun CI. Because this branch comes from a fork, it is not possible for us to push directly, but you can rerun by pushing an empty commit:
git commit --allow-empty -m "chore: trigger rerun" git push View detailed reasoning in Nx Cloud ↗
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Nx Cloud has identified a flaky task in your failed CI:#
Since the failure was identified as flaky, the solution is to rerun CI. Because this branch comes from a fork, it is not possible for us to push directly, but you can rerun by pushing an empty commit:
git commit --allow-empty -m "chore: trigger rerun" git push View detailed reasoning in Nx Cloud ↗
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Nx Cloud has identified a flaky task in your failed CI:#
Since the failure was identified as flaky, the solution is to rerun CI. Because this branch comes from a fork, it is not possible for us to push directly, but you can rerun by pushing an empty commit:
git commit --allow-empty -m "chore: trigger rerun" git push View detailed reasoning in Nx Cloud ↗
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)Actionable comments posted: 11
🧹 Nitpick comments (3)
e2e/solid-start/basic/rsbuild.config.ts (1)
7-23: ⚡ Quick winType-check prerender/sitemap config objects against plugin option contracts.
Given this is TypeScript config, bind these objects with
satisfiesto thetanstackStartoption types so API drift is caught at compile time.Suggested patch
+type StartOptions = NonNullable<Parameters<typeof tanstackStart>[0]> + const prerenderConfiguration = { enabled: true, filter: (page: { path: string }) => @@ - maxRedirects: 100, -} + maxRedirects: 100, +} satisfies NonNullable<StartOptions['prerender']> @@ tanstackStart({ prerender: isPrerender ? prerenderConfiguration : undefined, sitemap: isPrerender - ? { + ? ({ enabled: true, host: 'https://example.com', - } + } satisfies NonNullable<StartOptions['sitemap']>) : undefined, }),As per coding guidelines,
**/*.{ts,tsx}: Use TypeScript strict mode with extensive type safety.Also applies to: 35-40
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/solid-start/basic/rsbuild.config.ts` around lines 7 - 23, The prerenderConfiguration object is not type-checked against the plugin option contract; update it to use TypeScript's "satisfies" operator to bind it to the appropriate tanstackStart option type (the same contract used for plugin options) so API drift is caught at compile time — locate the prerenderConfiguration constant and any similar config objects (also around the other config block at lines ~35-40) and change their declarations to append "satisfies <TanstackStartOptionsType>" (use the exact exported type name from the tanstackStart plugin) so the compiler enforces the expected shape while keeping the inferred narrower types.packages/start-plugin-core/tests/build-sitemap.test.ts (1)
35-35: 💤 Low valueRepeated
as anycasts reduce type-safety coverage of the testsEvery test passes
startConfigasas any(lines 35, 74, 105, 131, 156, 177, 221), which silently allows structurally invalid input and defeats the TypeScript-strict-mode requirement for these tests.Consider exporting a minimal
DeepPartial<BuildSitemapOptions>or a dedicated test-fixture type so the test inputs remain typed. If the config type is intentionally unexported, at minimum useas unknown as BuildSitemapOptionsto at least require the cast to be explicit. As per coding guidelines,.tsfiles should use TypeScript strict mode with extensive type safety.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/build-sitemap.test.ts` at line 35, Replace the repeated unsafe "as any" casts for test inputs with a typed test fixture: define a minimal fixture type (e.g., DeepPartial<BuildSitemapOptions> or a TestBuildSitemapOptions) and update every startConfig usage (the objects currently cast with "as any") to be typed as that fixture or cast as "as unknown as BuildSitemapOptions" if the real type is unexported; change the seven occurrences (the casts at startConfig in build-sitemap.test.ts) so tests maintain TS strict-mode safety and avoid blanket "as any" casting while still allowing partial test objects.packages/start-plugin-core/src/rsbuild/virtual-modules.ts (1)
569-577: 💤 Low valueConsider mirroring the environment loop from
updateServerFnResolverintryUpdateServerFnResolverfor consistency.updateServerFnResolver(lines 550–567) iterates through server, prerender (if registered), and provider environments, whiletryUpdateServerFnResolveronly updates the server environment. If a prerender VMP is registered, the prerender resolver will silently diverge. Though the explicit-content call site is server-only today, mirroring the loop would prevent future issues and maintain consistency between the two methods.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/rsbuild/virtual-modules.ts` around lines 569 - 577, tryUpdateServerFnResolver currently only updates the server environment, which can diverge from updateServerFnResolver that loops server → prerender (if a prerender VMP is registered) → provider; change tryUpdateServerFnResolver to mirror updateServerFnResolver by iterating the same environments and updating lastResolverContentByEnvironment and calling tryWriteModule for each environment’s resolver path (e.g., paths.serverFnResolver, paths.prerenderFnResolver, paths.providerFnResolver), including the conditional check used in updateServerFnResolver for whether the prerender VMP is registered.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/start/framework/solid/guide/static-prerendering.md`: - Around line 78-79: Update the note explaining the default separate route-options bundling to explicitly call out the Nitro adapter exception: state that while Start defaults to building route options separately (prerender.separateRouteOptionsBundle = true), Nitro-based deployments/adapter keep this setting off for compatibility, so Nitro users should set or expect prerender.separateRouteOptionsBundle = false; modify the sentence around the existing mention of prerender.separateRouteOptionsBundle to include this Nitro-specific caveat and suggested wording for clarity. In `@e2e/react-start/basic/tests/prerendering.spec.ts`: - Around line 28-35: The marker-checking helper outputContainsMarker only looks at '.js' files and thus misses '.mjs' bundles; update the check in function outputContainsMarker (and the predicate that currently uses filePath.endsWith('.js')) to also include '.mjs' (e.g., accept files that end with '.js' or '.mjs') so prerender-only markers in .mjs server output are detected during the assertions. In `@e2e/solid-start/basic/rsbuild.config.ts`: - Around line 9-22: The prerender filter uses substring matching via page.path.includes(p) which can wrongly exclude routes like "/usersettings" when "/users" is in the list; update the filter (the filter function that references page.path.includes) to perform exact-or-boundary matching instead (e.g., compare full path equality or use a path-boundary regex or check segment boundaries) so only exact route matches or path-segment matches are excluded; keep the exclusion list (the array of p values) and replace the includes check with a robust equality/boundary check that treats "/users" as a full segment (e.g., equals or regex matching for end-of-string or slash) to avoid false positives. In `@e2e/vue-start/basic/rsbuild.config.ts`: - Around line 10-22: The filter predicate currently uses page.path.includes(p) which accidentally excludes any route containing strings like '/users' or '/search-params' (e.g., '/users/1'); update the check in the filter (the function using page: { path: string } and the array of excluded strings) to perform strict matching instead of substring matching — for example use page.path === p for exact entries and/or page.path.startsWith(p + '/') for prefix exclusions — and adjust the exclusion array entries ('/users', '/search-params', etc.) accordingly so only intended routes are skipped. In `@packages/start-plugin-core/src/post-build.ts`: - Around line 26-28: The expression computing spaOnly uses startConfig.prerender.enabled without optional chaining which can fail TypeScript strict checks; update the references to use optional chaining (e.g., startConfig.prerender?.enabled) wherever prerender.enabled is read (including the spaOnly assignment and the later check around prerender use) so the compiler knows the property access is guarded while preserving the same boolean logic involving startConfig.spa?.enabled and prerender enabled state. In `@packages/start-plugin-core/src/prerender-params-runner.ts`: - Around line 201-205: The generated page object is discarding route-level prerender defaults by assigning entry.prerender directly; change the return to merge route-level and entry-level prerender so entry values override defaults (similar to how sitemap is merged). Locate the return that currently sets prerender: entry.prerender and replace it with a merged value, e.g. use mergeOptions(options.prerender, entry.prerender) (or the existing merge helper used for sitemap) so dynamic pages inherit route defaults while allowing per-entry overrides. In `@packages/start-plugin-core/src/prerender.ts`: - Around line 64-70: The code is double-normalizing prerender paths: remove the extra call to validateAndNormalizePrerenderPages so paths are normalized only once by prerenderPages; specifically, stop reassigning startConfig.pages here (the block that builds routerBasePath/routerBaseUrl and calls validateAndNormalizePrerenderPages) because prerenderPages already invokes validateAndNormalizePrerenderPages after runPrerenderParams—leave routerBasePath/routerBaseUrl usage if needed but eliminate the duplicate normalize step to avoid decoding percent-encoded content twice (see validateAndNormalizePrerenderPages, prerenderPages, runPrerenderParams, and startConfig.pages). In `@packages/start-plugin-core/src/rsbuild/start-compiler-host.ts`: - Around line 80-83: The default environments array assigned to environments (from opts.environments) omits the prerender environment while later code checks for RSBUILD_ENVIRONMENT_NAMES.prerender; update the fallback so environments defaults to include { name: RSBUILD_ENVIRONMENT_NAMES.prerender, type: 'prerender' } alongside client and server to ensure the prerender branch in startCompilerHost (and any handling that checks for RSBUILD_ENVIRONMENT_NAMES.prerender) can run when opts.environments is omitted. In `@packages/start-plugin-core/tests/build-sitemap.test.ts`: - Around line 114-146: The test sets process.env.SITE_URL but still passes host: process.env.SITE_URL into buildSitemap, so it never exercises the env-fallback; to fix, remove the explicit host property from the startConfig.sitemap object passed to buildSitemap so the function (buildSitemap) will read process.env.SITE_URL at runtime and the existing try/finally env save/restore remains meaningful; update the test expectation to remain the same and keep temp dir setup and cleanup as-is. In `@packages/start-plugin-core/tests/prerender-params-runner.test.ts`: - Around line 334-339: The exact string assertion for the AbortController rejection is brittle across runtimes; update the test that constructs expectation from result (the line using expect(result).rejects.toThrow(...)) to assert against a regex like /operation was aborted/i instead of the exact string so it matches both Node and Bun; keep the existing process.emit('SIGTERM') and await expectation flow but replace the literal message in the toThrow call (refer to the expect(result).rejects.toThrow usage and the expectation variable) with a case-insensitive regex matching "operation was aborted". In `@packages/start-plugin-core/tests/rsbuild-post-build.test.ts`: - Around line 13-18: The beforeEach setup currently resets modules and clears __ROUTE_OPTIONS_LOADED and some env vars but doesn't clear the mutated global route tree; update the beforeEach to also delete or reset globalThis.TSS_PRERENDER_ROUTE_TREE so each test starts with a clean state—locate the beforeEach block and add removal of globalThis.TSS_PRERENDER_ROUTE_TREE (or set it to undefined/null) alongside the existing deletes. --- Nitpick comments: In `@e2e/solid-start/basic/rsbuild.config.ts`: - Around line 7-23: The prerenderConfiguration object is not type-checked against the plugin option contract; update it to use TypeScript's "satisfies" operator to bind it to the appropriate tanstackStart option type (the same contract used for plugin options) so API drift is caught at compile time — locate the prerenderConfiguration constant and any similar config objects (also around the other config block at lines ~35-40) and change their declarations to append "satisfies <TanstackStartOptionsType>" (use the exact exported type name from the tanstackStart plugin) so the compiler enforces the expected shape while keeping the inferred narrower types. In `@packages/start-plugin-core/src/rsbuild/virtual-modules.ts`: - Around line 569-577: tryUpdateServerFnResolver currently only updates the server environment, which can diverge from updateServerFnResolver that loops server → prerender (if a prerender VMP is registered) → provider; change tryUpdateServerFnResolver to mirror updateServerFnResolver by iterating the same environments and updating lastResolverContentByEnvironment and calling tryWriteModule for each environment’s resolver path (e.g., paths.serverFnResolver, paths.prerenderFnResolver, paths.providerFnResolver), including the conditional check used in updateServerFnResolver for whether the prerender VMP is registered. In `@packages/start-plugin-core/tests/build-sitemap.test.ts`: - Line 35: Replace the repeated unsafe "as any" casts for test inputs with a typed test fixture: define a minimal fixture type (e.g., DeepPartial<BuildSitemapOptions> or a TestBuildSitemapOptions) and update every startConfig usage (the objects currently cast with "as any") to be typed as that fixture or cast as "as unknown as BuildSitemapOptions" if the real type is unexported; change the seven occurrences (the casts at startConfig in build-sitemap.test.ts) so tests maintain TS strict-mode safety and avoid blanket "as any" casting while still allowing partial test objects.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
ff844a3b-c3ce-4c23-b7bf-144598cfcc65📥 Commits
Reviewing files that changed from the base of the PR and between 6f5afd7b7a8368ed3f39a90233e303167829a096 and 0c80382b11af88e892d47b021c7b8266bb2620b8.
📒 Files selected for processing (37)
docs/start/framework/react/guide/static-prerendering.mddocs/start/framework/solid/guide/static-prerendering.mde2e/react-start/basic/src/routes/prerender-params.$slug.tsxe2e/react-start/basic/tests/prerendering.spec.tse2e/solid-start/basic/rsbuild.config.tse2e/vue-start/basic/rsbuild.config.tspackages/start-plugin-core/src/constants.tspackages/start-plugin-core/src/global.d.tspackages/start-plugin-core/src/post-build.tspackages/start-plugin-core/src/prerender-params-runner.tspackages/start-plugin-core/src/prerender-route-options-env.tspackages/start-plugin-core/src/prerender.tspackages/start-plugin-core/src/rsbuild/planning.tspackages/start-plugin-core/src/rsbuild/plugin.tspackages/start-plugin-core/src/rsbuild/post-build.tspackages/start-plugin-core/src/rsbuild/start-compiler-host.tspackages/start-plugin-core/src/rsbuild/start-router-plugin.tspackages/start-plugin-core/src/rsbuild/types.tspackages/start-plugin-core/src/rsbuild/virtual-modules.tspackages/start-plugin-core/src/schema.tspackages/start-plugin-core/src/start-router-plugin/constants.tspackages/start-plugin-core/src/vite/planning.tspackages/start-plugin-core/src/vite/plugin.tspackages/start-plugin-core/src/vite/prerender.tspackages/start-plugin-core/src/vite/start-compiler-plugin/plugin.tspackages/start-plugin-core/src/vite/start-router-plugin/plugin.tspackages/start-plugin-core/tests/build-sitemap.test.tspackages/start-plugin-core/tests/post-server-build.test.tspackages/start-plugin-core/tests/prerender-params-runner.test.tspackages/start-plugin-core/tests/prerender-route-options-env.test.tspackages/start-plugin-core/tests/prerender-routes-plugin.test.tspackages/start-plugin-core/tests/prerender-ssrf.test.tspackages/start-plugin-core/tests/rsbuild-post-build.test.tspackages/start-plugin-core/tests/start-router-plugin-constants.test.tspackages/start-plugin-core/tests/vite-planning.test.tspackages/start-plugin-core/tests/vite-prerender.test.tspackages/start-server-core/src/createStartHandler.ts
docs/start/framework/solid/guide/static-prerendering.md lines 148 to 149Resolvedby nikuscs(GitHub profile, opens in a new tab)@@ -69,3 +75,5 @@6975 })7076 ```717778+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.79+⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Call out the Nitro exception in the default-behavior note.
This says separate route-options bundling is the default, but the PR behavior keeps it off for Nitro compatibility. Without that caveat, Nitro users will get the wrong expectation from this guide.
Suggested wording
-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. +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. Some adapters, such as Nitro, keep this disabled for compatibility. 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.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change148+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. Some adapters, such as Nitro, keep this disabled for compatibility. 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.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/start/framework/solid/guide/static-prerendering.md` around lines 78 - 79, Update the note explaining the default separate route-options bundling to explicitly call out the Nitro adapter exception: state that while Start defaults to building route options separately (prerender.separateRouteOptionsBundle = true), Nitro-based deployments/adapter keep this setting off for compatibility, so Nitro users should set or expect prerender.separateRouteOptionsBundle = false; modify the sentence around the existing mention of prerender.separateRouteOptionsBundle to include this Nitro-specific caveat and suggested wording for clarity.e2e/react-start/basic/tests/prerendering.spec.ts lines 28 to 35Resolvedby nikuscs(GitHub profile, opens in a new tab)@@ -11,0 +15,21 @@15+ 'server',16+)17+18+const prerenderOnlyBundleMarkers = [19+ 'server-only-prerender-marker',20+ 'top-level-prerender-literal-marker-should-not-ship',21+ 'top-level-imported-marker-slug',22+ 'top-level-import-call-marker-should-not-ship',23+ 'top-level-side-effect-prerender-marker-should-not-ship',24+ 'top-level-side-effect-slug',25+ '__TSR_PRERENDER_SIDE_EFFECT_MARKER',26+] as const27+28+function outputContainsMarker(dir: string, marker: string) {29+ return readdirSync(dir, { recursive: true }).some((relativePath) => {30+ const filePath = join(dir, String(relativePath))31+ return (32+ statSync(filePath).isFile() &&33+ filePath.endsWith('.js') &&34+ readFileSync(filePath, 'utf-8').includes(marker)35+ )⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Scan
.mjsbundles too in the marker check.outputContainsMarkeronly inspects.jsfiles, so these assertions will miss leaked prerender-only markers if a build emits.mjsserver output. That makes the new bundle-stripping coverage weaker than intended.♻️ Suggested change
function outputContainsMarker(dir: string, marker: string) { return readdirSync(dir, { recursive: true }).some((relativePath) => { const filePath = join(dir, String(relativePath)) return ( statSync(filePath).isFile() && - filePath.endsWith('.js') && + (filePath.endsWith('.js') || filePath.endsWith('.mjs')) && readFileSync(filePath, 'utf-8').includes(marker) ) }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/react-start/basic/tests/prerendering.spec.ts` around lines 28 - 35, The marker-checking helper outputContainsMarker only looks at '.js' files and thus misses '.mjs' bundles; update the check in function outputContainsMarker (and the predicate that currently uses filePath.endsWith('.js')) to also include '.mjs' (e.g., accept files that end with '.js' or '.mjs') so prerender-only markers in .mjs server output are detected during the assertions.✅ Addressed in commit 2cba39a
e2e/solid-start/basic/rsbuild.config.ts lines 9 to 22Resolvedby nikuscs(GitHub profile, opens in a new tab)@@ -2,3 +2,21 @@22 import { pluginBabel } from '@rsbuild/plugin-babel'33 import { pluginSolid } from '@rsbuild/plugin-solid'44 import { tanstackStart } from '@tanstack/solid-start/plugin/rsbuild'5+import { isPrerender } from './tests/utils/isPrerender'6+7+const prerenderConfiguration = {8+ enabled: true,9+ filter: (page: { path: string }) =>10+ ![11+ '/this-route-does-not-exist',12+ '/redirect',13+ '/i-do-not-exist',14+ '/not-found',15+ '/specialChars/search',16+ '/specialChars/hash',17+ '/specialChars/malformed',18+ '/search-params/default',19+ '/transition',20+ '/users',21+ ].some((p) => page.path.includes(p)),22+ maxRedirects: 100,⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Avoid substring matching in prerender route exclusion.
On Line 21,
page.path.includes(p)can exclude unintended routes (for example,/usersettingsmatches/users). Use exact-or-boundary matching to avoid false positives in prerender filtering.Suggested patch
const prerenderConfiguration = { enabled: true, filter: (page: { path: string }) => ![ @@ '/transition', '/users', - ].some((p) => page.path.includes(p)), + ].some((p) => page.path === p || page.path.startsWith(`${p}/`)), maxRedirects: 100, }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change9- filter: (page: { path: string }) =>10- ![11- '/this-route-does-not-exist',12- '/redirect',13- '/i-do-not-exist',14- '/not-found',15- '/specialChars/search',16- '/specialChars/hash',17- '/specialChars/malformed',18- '/search-params/default',19- '/transition',20- '/users',21- ].some((p) => page.path.includes(p)),22- maxRedirects: 100,9+ filter: (page: { path: string }) =>10+ ![11+ '/this-route-does-not-exist',12+ '/redirect',13+ '/i-do-not-exist',14+ '/not-found',15+ '/specialChars/search',16+ '/specialChars/hash',17+ '/specialChars/malformed',18+ '/search-params/default',19+ '/transition',20+ '/users',21+ ].some((p) => page.path === p || page.path.startsWith(`${p}/`)),22+ maxRedirects: 100,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/solid-start/basic/rsbuild.config.ts` around lines 9 - 22, The prerender filter uses substring matching via page.path.includes(p) which can wrongly exclude routes like "/usersettings" when "/users" is in the list; update the filter (the filter function that references page.path.includes) to perform exact-or-boundary matching instead (e.g., compare full path equality or use a path-boundary regex or check segment boundaries) so only exact route matches or path-segment matches are excluded; keep the exclusion list (the array of p values) and replace the includes check with a robust equality/boundary check that treats "/users" as a full segment (e.g., equals or regex matching for end-of-string or slash) to avoid false positives.✅ Addressed in commit 2cba39a
e2e/vue-start/basic/rsbuild.config.ts lines 10 to 22OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -5,3 +5,18 @@55 import { tanstackStart } from '@tanstack/vue-start/plugin/rsbuild'66 import { isPrerender } from './tests/utils/isPrerender'778+const prerenderConfiguration = {9+ enabled: true,10+ filter: (page: { path: string }) =>11+ ![12+ '/this-route-does-not-exist',13+ '/redirect',14+ '/i-do-not-exist',15+ '/not-found',16+ '/specialChars/search',17+ '/specialChars/hash',18+ '/specialChars/malformed',19+ '/search-params', // search-param routes have dynamic content based on query params20+ '/transition',21+ '/users',22+ ].some((p) => page.path.includes(p)),⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
page.path.includes(p)may unintentionally exclude sub-routes of excluded paths.The exclusion list entry
'/users'(and similarly'/search-params') uses a substring match, so any route whose path contains that string — e.g./users/1,/users/profile, or a hypothetical/search-params-extended— is also silently excluded from prerendering. In this E2E fixture that could mask test failures if dynamic/users/:idroutes are meant to be exercised viaprerenderParams.Consider switching to an exact-match or prefix-anchored check to limit unintended exclusions:
🛡️ Proposed fix: use strict equality or startsWith with a trailing slash
- filter: (page: { path: string }) => - ![ - '/this-route-does-not-exist', - '/redirect', - '/i-do-not-exist', - '/not-found', - '/specialChars/search', - '/specialChars/hash', - '/specialChars/malformed', - '/search-params', // search-param routes have dynamic content based on query params - '/transition', - '/users', - ].some((p) => page.path.includes(p)), + filter: (page: { path: string }) => + ![ + '/this-route-does-not-exist', + '/redirect', + '/i-do-not-exist', + '/not-found', + '/specialChars/search', + '/specialChars/hash', + '/specialChars/malformed', + '/search-params', // search-param routes have dynamic content based on query params + '/transition', + '/users', + ].some((p) => page.path === p || page.path.startsWith(p + '/')),📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change10- filter: (page: { path: string }) =>11- ![12- '/this-route-does-not-exist',13- '/redirect',14- '/i-do-not-exist',15- '/not-found',16- '/specialChars/search',17- '/specialChars/hash',18- '/specialChars/malformed',19- '/search-params', // search-param routes have dynamic content based on query params20- '/transition',21- '/users',22- ].some((p) => page.path.includes(p)),10+ filter: (page: { path: string }) =>11+ ![12+ '/this-route-does-not-exist',13+ '/redirect',14+ '/i-do-not-exist',15+ '/not-found',16+ '/specialChars/search',17+ '/specialChars/hash',18+ '/specialChars/malformed',19+ '/search-params', // search-param routes have dynamic content based on query params20+ '/transition',21+ '/users',22+ ].some((p) => page.path === p || page.path.startsWith(p + '/')),🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/vue-start/basic/rsbuild.config.ts` around lines 10 - 22, The filter predicate currently uses page.path.includes(p) which accidentally excludes any route containing strings like '/users' or '/search-params' (e.g., '/users/1'); update the check in the filter (the function using page: { path: string } and the array of excluded strings) to perform strict matching instead of substring matching — for example use page.path === p for exact entries and/or page.path.startsWith(p + '/') for prefix exclusions — and adjust the exclusion array entries ('/users', '/search-params', etc.) accordingly so only intended routes are skipped.✅ Addressed in commit 2cba39a
packages/start-plugin-core/src/post-build.ts lines 30 to 32Resolvedby nikuscs(GitHub profile, opens in a new tab)@@ -19,9 +19,10 @@1919 ...startConfig.prerender,2020 enabled:2121 startConfig.prerender?.enabled ??22- startConfig.pages.some((d) =>23- typeof d === 'string' ? false : !!d.prerender?.enabled,24- ),22+ startConfig.pages.some((page) => page.prerender?.enabled),2523 }2624 }272526+ const spaOnly = Boolean(27+ startConfig.spa?.enabled && startConfig.prerender.enabled !== true,28+ )⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Find TanStackStartOutputConfig and check if prerender is optional rg -n 'TanStackStartOutputConfig' --type ts -A 30 | grep -A 25 'interface TanStackStartOutputConfig\|type TanStackStartOutputConfig'Repository: TanStack/router
Length of output: 2116
🏁 Script executed:
#!/bin/bash # Find the parseStartConfig function definition rg -n 'export.*parseStartConfig|function parseStartConfig' packages/start-plugin-core/src/schema.ts -A 5Repository: TanStack/router
Length of output: 545
🏁 Script executed:
#!/bin/bash # Look for the schema definition with prerender field rg -n 'prerender' packages/start-plugin-core/src/schema.ts -B 2 -A 2 | head -80Repository: TanStack/router
Length of output: 733
🏁 Script executed:
#!/bin/bash # View the post-build.ts file around lines 17-28 and 65 to see actual code cat -n packages/start-plugin-core/src/post-build.ts | sed -n '15,75p'Repository: TanStack/router
Length of output: 1922
Use optional chaining for
startConfig.prerender.enabledto comply with TypeScript strict modeprerenderis optional inTanStackStartOutputConfig(defined in schema.ts with.optional()). Although both branches of the condition at line 17 logically ensurestartConfig.prerenderis defined before use, TypeScript's control-flow narrowing does not reliably track optional properties through optional-chaining conditions and conditional assignments. At line 27,startConfig.prerender.enabledshould use optional chaining to pass strict mode checks. The same applies at line 65.Proposed fixes
const spaOnly = Boolean( - startConfig.spa?.enabled && startConfig.prerender.enabled !== true, + startConfig.spa?.enabled && startConfig.prerender?.enabled !== true, )- if (startConfig.prerender.enabled) { + if (startConfig.prerender?.enabled) {📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change30+ const spaOnly = Boolean(31+ startConfig.spa?.enabled && startConfig.prerender?.enabled !== true,32+ )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/post-build.ts` around lines 26 - 28, The expression computing spaOnly uses startConfig.prerender.enabled without optional chaining which can fail TypeScript strict checks; update the references to use optional chaining (e.g., startConfig.prerender?.enabled) wherever prerender.enabled is read (including the spaOnly assignment and the later check around prerender use) so the compiler knows the property access is guarded while preserving the same boolean logic involving startConfig.spa?.enabled and prerender enabled state.✅ Addressed in commit 2cba39a
packages/start-plugin-core/src/prerender-params-runner.ts lines 201 to 205OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +185,21 @@185+ const { interpolatedPath, isMissingParams, usedParams } = interpolatePath({186+ path: route.path,187+ params: entry.params,188+ })189+190+ if (191+ isMissingParams ||192+ Object.entries(usedParams).some(193+ ([key, value]) => key !== '*' && value == null,194+ )195+ ) {196+ throw new Error(197+ `Missing prerenderParams values for route ${route.routePath}`,198+ )199+ }200+201+ return {202+ path: interpolatedPath + stringifySearch(entry.search),203+ sitemap: mergeOptions(options.sitemap, entry.sitemap),204+ prerender: entry.prerender,205+ }⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Merge route-level
prerenderdefaults into generated pages.Generated dynamic pages currently keep route-level
sitemapdefaults, but they drop route-levelprerenderconfig entirely by assigning onlyentry.prerender. That breaks the “per-entry override” behavior for dynamic routes because entry-specific values replace the whole prerender config instead of overriding the route default.Suggested fix
return { path: interpolatedPath + stringifySearch(entry.search), sitemap: mergeOptions(options.sitemap, entry.sitemap), - prerender: entry.prerender, + prerender: mergeOptions(options.prerender, entry.prerender), }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change201- return {202- path: interpolatedPath + stringifySearch(entry.search),203- sitemap: mergeOptions(options.sitemap, entry.sitemap),204- prerender: entry.prerender,205- }201+ return {202+ path: interpolatedPath + stringifySearch(entry.search),203+ sitemap: mergeOptions(options.sitemap, entry.sitemap),204+ prerender: mergeOptions(options.prerender, entry.prerender),205+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 201 - 205, The generated page object is discarding route-level prerender defaults by assigning entry.prerender directly; change the return to merge route-level and entry-level prerender so entry values override defaults (similar to how sitemap is merged). Locate the return that currently sets prerender: entry.prerender and replace it with a merged value, e.g. use mergeOptions(options.prerender, entry.prerender) (or the existing merge helper used for sitemap) so dynamic pages inherit route defaults while allowing per-entry overrides.✅ Addressed in commit 2cba39a
packages/start-plugin-core/src/prerender.ts lines 64 to 70OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -48,5 +54,17 @@54+ pages,55+ logger,56+ filter: startConfig.prerender.filter,57+ prerenderParamsTimeout: startConfig.prerender.prerenderParamsTimeout,58+ })59+ }486049- startConfig.pages = validateAndNormalizePrerenderPages(50- startConfig.pages,51- routerBaseUrl,52- )61+ startConfig.pages = pages62+ }63+64+ const routerBasePath = joinURL('/', startConfig.router.basepath ?? '')65+ const routerBaseUrl = new URL(routerBasePath, 'http://localhost')66+67+ startConfig.pages = validateAndNormalizePrerenderPages(68+ startConfig.pages,69+ routerBaseUrl,70+ )⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Avoid normalizing prerender paths twice.
prerenderPages()already callsvalidateAndNormalizePrerenderPages, so normalizingstartConfig.pageshere adds a second decode pass. That can corrupt paths containing literal percent-encoded content afterrunPrerenderParamsexpands them, e.g.%25E2%259C%2593can collapse to✓on the second pass. Keep the normalization in one place only.Suggested fix
- const routerBasePath = joinURL('/', startConfig.router.basepath ?? '') - const routerBaseUrl = new URL(routerBasePath, 'http://localhost') - - startConfig.pages = validateAndNormalizePrerenderPages( - startConfig.pages, - routerBaseUrl, - ) - const pages = await prerenderPages({ outputDir: handler.getClientOutputDirectory(), })📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change64- const routerBasePath = joinURL('/', startConfig.router.basepath ?? '')65- const routerBaseUrl = new URL(routerBasePath, 'http://localhost')66-67- startConfig.pages = validateAndNormalizePrerenderPages(68- startConfig.pages,69- routerBaseUrl,70- )64+🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender.ts` around lines 64 - 70, The code is double-normalizing prerender paths: remove the extra call to validateAndNormalizePrerenderPages so paths are normalized only once by prerenderPages; specifically, stop reassigning startConfig.pages here (the block that builds routerBasePath/routerBaseUrl and calls validateAndNormalizePrerenderPages) because prerenderPages already invokes validateAndNormalizePrerenderPages after runPrerenderParams—leave routerBasePath/routerBaseUrl usage if needed but eliminate the duplicate normalize step to avoid decoding percent-encoded content twice (see validateAndNormalizePrerenderPages, prerenderPages, runPrerenderParams, and startConfig.pages).✅ Addressed in commit 2cba39a
packages/start-plugin-core/src/rsbuild/start-compiler-host.ts lines 80 to 83OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -73,10 +77,7 @@7377 const isDev = api.context.action === 'dev'7478 const mode = isDev ? 'dev' : 'build'757976- const environments: Array<{77- name: string78- type: 'client' | 'server'79- }> = [80+ const environments = opts.environments ?? [8081 { name: RSBUILD_ENVIRONMENT_NAMES.client, type: 'client' },8182 { name: RSBUILD_ENVIRONMENT_NAMES.server, type: 'server' },8283 ]⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Verify RSBUILD_ENVIRONMENT_NAMES shape and whether callers omit environments rg -n "RSBUILD_ENVIRONMENT_NAMES" --type=ts -A3 # Find all call sites of registerStartCompilerTransforms to see if any omit environments rg -n "registerStartCompilerTransforms" --type=ts -A10Repository: TanStack/router
Length of output: 23004
🏁 Script executed:
# Check if registerStartCompilerTransforms is exported publicly rg "export.*registerStartCompilerTransforms" --type=ts # Search for all references to registerStartCompilerTransforms throughout the codebase rg "registerStartCompilerTransforms" --type=tsRepository: TanStack/router
Length of output: 496
Inconsistency: default environments should include prerender to match the code's handling of it.
The default fallback (lines 80–83) registers only
clientandserverenvironments, but the code at lines 96–97 checks for and handlesRSBUILD_ENVIRONMENT_NAMES.prerender. While this isn't a bug in current usage (the only call site inplugin.ts:255explicitly provides all three environments), the mismatch creates a consistency issue: ifopts.environmentsis ever omitted, the prerender branch will never be reached even though the code is prepared to handle it.For consistency and to future-proof the function, add
prerenderto the default:Proposed fix
const environments = opts.environments ?? [ { name: RSBUILD_ENVIRONMENT_NAMES.client, type: 'client' }, + { name: RSBUILD_ENVIRONMENT_NAMES.prerender, type: 'server' }, { name: RSBUILD_ENVIRONMENT_NAMES.server, type: 'server' }, ]🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/rsbuild/start-compiler-host.ts` around lines 80 - 83, The default environments array assigned to environments (from opts.environments) omits the prerender environment while later code checks for RSBUILD_ENVIRONMENT_NAMES.prerender; update the fallback so environments defaults to include { name: RSBUILD_ENVIRONMENT_NAMES.prerender, type: 'prerender' } alongside client and server to ensure the prerender branch in startCompilerHost (and any handling that checks for RSBUILD_ENVIRONMENT_NAMES.prerender) can run when opts.environments is omitted.✅ Addressed in commit 2cba39a
packages/start-plugin-core/tests/build-sitemap.test.ts lines 114 to 146OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ enabled: true,127+ host: process.env.SITE_URL,128+ outputPath: 'sitemap.xml',129+ },130+ pages: [{ path: '/guide/start' }],131+ } as any,132+ })133+ } finally {134+ if (previousSiteUrl === undefined) {135+ delete process.env.SITE_URL136+ } else {137+ process.env.SITE_URL = previousSiteUrl138+ }139+ }140+141+ const sitemap = readFileSync(join(publicDir, 'sitemap.xml'), 'utf-8')142+143+ expect(sitemap).toContain(144+ '<loc>https://deploy.example.com/guide/start</loc>',145+ )146+ })⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Env-test machinery is either dead code or tests the wrong thing
process.env.SITE_URLis set on line 119, then read back on line 127 ashost: process.env.SITE_URL. Because JavaScript evaluates the object literal at call time,buildSitemapalways receiveshost: 'https://deploy.example.com'— an ordinary string. Thetry/finallyenv save/restore block on lines 118–139 adds real complexity but exercises no different code path than the other host tests.There are two possible intent-aligned fixes:
Option A — If the goal is to test that
buildSitemapfalls back toSITE_URLwhen no explicithostis configured, removehostfrom the sitemap config:🐛 Option A — test env-variable fallback
- process.env.SITE_URL = 'https://deploy.example.com' + process.env.TANSTACK_START_SITE_URL = 'https://deploy.example.com' // or whatever key buildSitemap reads try { buildSitemap({ publicDir, startConfig: { sitemap: { enabled: true, - host: process.env.SITE_URL, outputPath: 'sitemap.xml', }, pages: [{ path: '/guide/start' }], } as any, }) } finally { - if (previousSiteUrl === undefined) { - delete process.env.SITE_URL - } else { - process.env.SITE_URL = previousSiteUrl - } + // restore appropriately }Option B — If there is no env-fallback behaviour and the test only intends to verify URL construction with a value that happens to come from an env var, remove the env machinery entirely:
🧹 Option B — eliminate dead env machinery
- const previousSiteUrl = process.env.SITE_URL - process.env.SITE_URL = 'https://deploy.example.com' - - try { - buildSitemap({ - publicDir, - startConfig: { - sitemap: { - enabled: true, - host: process.env.SITE_URL, - outputPath: 'sitemap.xml', - }, - pages: [{ path: '/guide/start' }], - } as any, - }) - } finally { - if (previousSiteUrl === undefined) { - delete process.env.SITE_URL - } else { - process.env.SITE_URL = previousSiteUrl - } - } + buildSitemap({ + publicDir, + startConfig: { + sitemap: { + enabled: true, + host: 'https://deploy.example.com', + outputPath: 'sitemap.xml', + }, + pages: [{ path: '/guide/start' }], + } as any, + })📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change114+ it('uses a host supplied from the environment', () => {115+ const publicDir = mkdtempSync(join(tmpdir(), 'tanstack-start-sitemap-'))116+ tempDirs.push(publicDir)117+118+ buildSitemap({119+ publicDir,120+ startConfig: {121+ sitemap: {122+ enabled: true,123+ host: 'https://deploy.example.com',124+ outputPath: 'sitemap.xml',125+ },126+ pages: [{ path: '/guide/start' }],127+ } as any,128+ })129+130+ const sitemap = readFileSync(join(publicDir, 'sitemap.xml'), 'utf-8')131+132+ expect(sitemap).toContain(133+ '<loc>https://deploy.example.com/guide/start</loc>',134+ )135+ })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/build-sitemap.test.ts` around lines 114 - 146, The test sets process.env.SITE_URL but still passes host: process.env.SITE_URL into buildSitemap, so it never exercises the env-fallback; to fix, remove the explicit host property from the startConfig.sitemap object passed to buildSitemap so the function (buildSitemap) will read process.env.SITE_URL at runtime and the existing try/finally env save/restore remains meaningful; update the test expectation to remain the same and keep temp dir setup and cleanup as-is.✅ Addressed in commit 2cba39a
packages/start-plugin-core/tests/prerender-params-runner.test.ts lines 334 to 339OutdatedResolvedby nikuscs(GitHub profile, opens in a new tab)@@ -0,0 +319,21 @@319+ reject(new Error('signal aborted'))320+ })321+ })322+ })323+ const routeTree = createRouteTree({324+ '/products/$slug': {325+ prerenderParams,326+ },327+ })328+329+ const result = runPrerenderParams({330+ routeTree,331+ pages: [],332+ logger,333+ })334+ const expectation = expect(result).rejects.toThrow(335+ 'This operation was aborted',336+ )337+338+ process.emit('SIGTERM')339+ await expectation⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
cat -n packages/start-plugin-core/tests/prerender-params-runner.test.ts | sed -n '330,345p'Repository: TanStack/router
Length of output: 550
🌐 Web query:
AbortController "This operation was aborted" message Node.js Bun runtime differences💡 Result:
In Node.js, when an AbortController aborts an operation (e.g., timers/promises.setTimeout or fetch), the error is typically a DOMException [AbortError]: "This operation was aborted" [1][2][3]. The AbortController.abort itself throws or causes a DOMException with this message as the default when no reason is provided [4][5]. In contrast, Bun produces an AbortError: "The operation was aborted" [1]. This difference is evident in direct side-by-side comparisons using node:timers/promises [1]. Both have code: "ABORT_ERR" [1]. Bun aims for web standard compatibility but shows slight variations in error formatting and historical bugs (e.g., uncaught aborts crashing processes in older versions, now fixed) [1][6][7]. No official docs specify the exact message difference, but GitHub issues confirm it via repros [1].
Citations:
- 1: https://github.com/oven-sh/bun/issues/14742
- 2: https://blog.appsignal.com/2025/02/12/managing-asynchronous-operations-in-nodejs-with-abortcontroller.html
- 3: https://github.com/nodejs/node/issues/40692?timeline_page=1
- 4: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort
- 5: https://github.com/nodejs/node/issues/33540
- 6: https://github.com/oven-sh/bun/issues/9429
- 7: https://github.com/oven-sh/bun/issues/5021
🌐 Web query:
Vitest expect rejects toThrow regex pattern matching AbortError💡 Result:
In Vitest, to assert that an async operation (a rejected promise) fails with an AbortError and that the error message matches a regex, use.rejects + toThrowError (or toThrow) with a RegExp. Example: const controller = new AbortController const p = fetch('/resource', { signal: controller.signal }) controller.abort await expect(p).rejects.toThrowError(/Abort/i) Why this works (and common gotchas): 1) Vitest’s expect.toThrow/toThrowError accepts a RegExp meaning “error message matches the pattern” [1]. 2) For async code, Vitest explicitly documents using rejects correctly unwraps the promise, and shows using await expect(promise).rejects.toThrowError [1]. 3) You must not call the function directly when testing sync throws—you generally wrap it in a function—but for rejected promises you use rejects as shown above [1]. About “rejects.toThrow regex AbortError”: - Vitest documents “toThrowError” behavior; “toThrow” is listed as an alias [2]. - Your matcher should be a RegExp against the error message (or a string substring) rather than expecting the matcher to validate the error type/name directly [1]. If you specifically need to match the error’s identity (e.g., DOMException.name === 'AbortError') rather than just its message, you’ll need a matcher that inspects that property (because the documented RegExp option only specifies message matching) [1].
Citations:
Use a regex pattern to avoid brittle assertion on runtime-specific error messages.
AbortControllerrejection messages differ between Node.js ("This operation was aborted") and Bun ("The operation was aborted"). The current exact string assertion will fail in Bun, especially relevant given the PR notes Bun wasn't tested locally.Suggested fix
- const expectation = expect(result).rejects.toThrow( - 'This operation was aborted', - ) + const expectation = expect(result).rejects.toThrow(/aborted/i)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change334- const expectation = expect(result).rejects.toThrow(335- 'This operation was aborted',336- )337-338- process.emit('SIGTERM')339- await expectation334+ const expectation = expect(result).rejects.toThrow(/aborted/i)335+336+ process.emit('SIGTERM')337+ await expectation🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/prerender-params-runner.test.ts` around lines 334 - 339, The exact string assertion for the AbortController rejection is brittle across runtimes; update the test that constructs expectation from result (the line using expect(result).rejects.toThrow(...)) to assert against a regex like /operation was aborted/i instead of the exact string so it matches both Node and Bun; keep the existing process.emit('SIGTERM') and await expectation flow but replace the literal message in the toThrow call (refer to the expect(result).rejects.toThrow usage and the expectation variable) with a case-insensitive regex matching "operation was aborted".✅ Addressed in commit 2cba39a
packages/start-plugin-core/tests/rsbuild/post-build.test.ts lines 13 to 19Resolvedby nikuscs(GitHub profile, opens in a new tab)@@ -10,3 +10,9 @@1010 }))11111212 describe('postBuildWithRsbuild', () => {13+ beforeEach(() => {14+ vi.resetModules()15+ delete (globalThis as any).__ROUTE_OPTIONS_LOADED16+ delete process.env.TSS_PRERENDERING17+ delete process.env.TSS_CLIENT_OUTPUT_DIR18+ })⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Reset
TSS_PRERENDER_ROUTE_TREEin test setup too.The new prerender bundle path mutates
globalThis.TSS_PRERENDER_ROUTE_TREE, butbeforeEachonly clears env vars and__ROUTE_OPTIONS_LOADED. If a prior case populates the route tree, later assertions can pass or fail on leaked global state instead of the current fixture.Suggested fix
beforeEach(() => { vi.resetModules() delete (globalThis as any).__ROUTE_OPTIONS_LOADED + delete globalThis.TSS_PRERENDER_ROUTE_TREE delete process.env.TSS_PRERENDERING delete process.env.TSS_CLIENT_OUTPUT_DIR })📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change13+ beforeEach(() => {14+ vi.resetModules()15+ delete (globalThis as any).__ROUTE_OPTIONS_LOADED16+ delete (globalThis as any).TSS_PRERENDER_ROUTE_TREE17+ delete process.env.TSS_PRERENDERING18+ delete process.env.TSS_CLIENT_OUTPUT_DIR19+ })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/rsbuild-post-build.test.ts` around lines 13 - 18, The beforeEach setup currently resets modules and clears __ROUTE_OPTIONS_LOADED and some env vars but doesn't clear the mutated global route tree; update the beforeEach to also delete or reset globalThis.TSS_PRERENDER_ROUTE_TREE so each test starts with a clean state—locate the beforeEach block and add removal of globalThis.TSS_PRERENDER_ROUTE_TREE (or set it to undefined/null) alongside the existing deletes.✅ Addressed in commit 2cba39a
🧹 Nitpick comments (9)
packages/start-client-core/src/tests/prerenderParams.test-d.ts (1)
13-227: ⚡ Quick winAdd type tests for async
prerenderParamsand per-entrysitemapmetadata.This suite currently locks sync callback typing and route-level sitemap typing, but not the async callback form or
entry.sitemaptyping on returned entries. Adding oneasync prerenderParamscase and one entry-level sitemap case would better protect the new API surface from type regressions.As per coding guidelines, "Use TypeScript strict mode with extensive type safety."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-client-core/src/tests/prerenderParams.test-d.ts` around lines 13 - 227, Add two type tests: one for an async prerenderParams function and one asserting per-entry sitemap typing. Create an options object whose prerenderParams is async (async () => [...]) and use it with FileBaseRouteOptions to derive Entry = Awaited<ReturnType<NonNullable<typeof options.prerenderParams>>>[number], then expectTypeOf<Entry['params']>() and expectTypeOf<Entry['sitemap']>() to match expected shapes (e.g., priority: number, changefreq: 'weekly' | ...). Also add a returned entry that includes an entry-level sitemap field to ensure per-entry sitemap is type-checked against the route-level sitemap shape.packages/start-plugin-core/tests/build-sitemap.test.ts (1)
147-212: 💤 Low valuewrites advanced sitemap metadatadoes not assert the<loc>URL.All namespace, image, news, and alternate-ref assertions are present, but no assertion verifies the
<loc>element for/news/router-launch. IfbuildSitemapever emits a malformed URL for this entry the test would not catch it.✅ Suggested addition
const sitemap = readFileSync(join(publicDir, 'sitemap.xml'), 'utf-8') + expect(sitemap).toContain( + '<loc>https://example.com/news/router-launch</loc>', + ) expect(sitemap).toContain( 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"', )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/build-sitemap.test.ts` around lines 147 - 212, The test "writes advanced sitemap metadata" for buildSitemap is missing an assertion for the <loc> element; update the test in build-sitemap.test.ts (inside the it block that calls buildSitemap and reads sitemap into the sitemap variable) to assert that the sitemap contains the canonical URL for the page path (e.g. expect(sitemap).toContain('<loc>https://example.com/news/router-launch</loc>') so the produced <loc> element for the /news/router-launch entry is validated).e2e/react-start/basic/tests/prerendering.spec.ts (2)
99-99: ⚡ Quick winAvoid asserting React’s empty-comment serialization.
These checks are tied to the current
<!-- -->HTML shape, so they can fail on harmless SSR serialization changes even when the prerendered content is still correct. Matching the text with the same regex style used on Line 141 and Line 142 would make this coverage much less brittle.♻️ Suggested change
- expect(html).toContain('Nested prerendered slug: <!-- -->under-layout') + expect(html).toMatch( + /Nested prerendered slug:(?:\s|<!--[^>]*-->)*under-layout/, + ) - expect(html).toContain('Prerendered slug: <!-- -->hello-world') + expect(html).toMatch( + /Prerendered slug:(?:\s|<!--[^>]*-->)*hello-world/, + )Also applies to: 108-108
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/react-start/basic/tests/prerendering.spec.ts` at line 99, The assertion in prerendering.spec.ts that expects the literal string "Nested prerendered slug: <!-- -->under-layout" is brittle because it depends on React's empty-comment HTML serialization; replace that expect(html).toContain(...) check with a regex-based assertion (as used on the other assertions around Line 141/142) that matches the visible text regardless of the empty-comment node (e.g., assert that html matches /Nested prerendered slug:\s*under-layout/), and apply the same change for the similar assertion at the other occurrence (the expect call containing the same comment-based string).
203-216: ⚡ Quick winScope sitemap metadata assertions to the matching
<url>entry.As written, this can still pass if
lastmod/priority/changefreqend up on the wrong sitemap entry, because each value is asserted independently. Since this PR adds per-entry sitemap overrides, it would be safer to assert against the full<url>block for each route or parse the XML and check the fields on the matching<loc>.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@e2e/react-start/basic/tests/prerendering.spec.ts` around lines 203 - 216, The test currently asserts sitemap metadata values independently which can misattribute values to the wrong <url>; update the assertions to scope them to the matching <url> block by locating the <url> node for each <loc> and then asserting its child tags (e.g., <lastmod>, <priority>, <changefreq>) match expected values. In the prerendering.spec.ts test use the sitemap string (sitemap) and either parse the XML (e.g., a lightweight XML parser) to find the <url> element whose <loc> equals the target URL and assert its children, or assert against the full expected <url> block string for each route (e.g., the block containing '<loc>https://example.com/prerender-params/hello-world</loc>') so lastmod/priority/changefreq are validated within the same <url>.packages/start-plugin-core/tests/prerender-params-runner.test.ts (1)
4-6: 💤 Low valueConsider resetting the shared logger spy between tests.
The
logger.warnspy persists across tests; only the static-route test (line 456) explicitly callsmockClear(). If future tests addtoHaveBeenCalledWithor call-count assertions, residue from earlier tests could cause flaky behavior. AbeforeEach(() => logger.warn.mockClear())would make tests independent of order.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/tests/prerender-params-runner.test.ts` around lines 4 - 6, Add a beforeEach hook to clear the shared logger spy so tests don't leak calls: call logger.warn.mockClear() (or vi.clearAllMocks()) in a beforeEach at the top of the test suite that contains the logger definition so logger.warn is reset before each test; this targets the logger.warn spy used in the tests (and keeps the static-route test's explicit mockClear safe to keep).packages/start-plugin-core/src/prerender-params-runner.ts (3)
110-120: 💤 Low valueProcess signal handlers will swallow the first SIGINT/SIGTERM during prerender.
process.onceensures the handler fires only on the first signal - subsequent signals revert to default (process termination). However, whilerunPrerenderParamsis running, the first SIGINT/SIGTERM aborts the prerenderParams controller but does NOT terminate the process. This is likely intentional (graceful abort), but it means a single Ctrl+C will be effectively swallowed: the prerenderParams call rejects with the abort reason, then the surroundingprerender()flow continues with that error. Users may need to press Ctrl+C twice. Consider documenting this behavior or re-emitting the signal after abort if termination is the intent.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 110 - 120, The current attachProcessAbortHandlers function uses process.once('SIGINT'/'SIGTERM') to call controller.abort(), which aborts the prerender controller but swallows the first signal (requiring a second Ctrl+C to terminate); update attachProcessAbortHandlers (or the call site around runPrerenderParams/prerender) to either re-emit the original signal after calling controller.abort() (e.g., restore default behavior or call process.kill(process.pid, signal) so the process will terminate on the first signal) or explicitly document this single-signal-graceful-abort behavior in the prerender/runPrerenderParams docs so users know they must press Ctrl+C twice — locate attachProcessAbortHandlers, the abort callback that calls controller.abort(), and the runPrerenderParams/prerender flow to implement the chosen change.
231-238: 💤 Low valuemergeOptionsis shallow - nested sitemap fields will be replaced wholesale.mergeOptionsonly does a shallow spread, which is correct for top-level keys but means nested objects/arrays (e.g.sitemap.images,sitemap.news,sitemap.alternateRefs) are replaced rather than merged when both base and override define them. This appears intentional given the test expectations, but worth a brief docstring noting the behavior so future contributors don't assume deep-merge semantics for nested arrays like alternateRefs/images.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 231 - 238, The mergeOptions function currently performs a shallow merge for T extends RouteSitemapOptions | RoutePrerenderOptions so nested sitemap fields (e.g. sitemap.images, sitemap.news, sitemap.alternateRefs) in override will replace those in base rather than being deep-merged; add a concise docstring above mergeOptions that states this behavior explicitly (shallow merge only, nested objects/arrays are replaced), mention the relevant types (RouteSitemapOptions, RoutePrerenderOptions) and the specific nested keys, and optionally note that tests expect this semantics so future contributors won't assume deep-merge behavior.
240-242: 💤 Low valueisDynamicPathcheck aligns with TanStack Router's own pattern detection.The
path.includes('$')check mirrors TanStack Router's own approach ininterpolatePath(router-core/src/path.ts:260), which uses the same quick filter before detailedparseSegmentparsing for complex patterns like$param,{-$optional}, and{$}wildcards. While a more precise regex could be used, the current implementation is pragmatic and consistent with how TanStack Router itself detects dynamic paths. The risk of misclassifying literal$in developer-defined route patterns is minimal since URL paths rarely contain unencoded$characters.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-params-runner.ts` around lines 240 - 242, The current isDynamicPath function uses a simple dollar-sign presence check (function isDynamicPath(path: string) { return path.includes('$') }) which matches TanStack Router's pragmatic quick-filter behavior; leave this implementation unchanged to remain consistent with TanStack Router's intercept in interpolatePath and avoid overcomplicating with a stricter regex unless you need to handle literal unencoded '$' in paths—so keep isDynamicPath as-is (no code change).packages/start-plugin-core/src/prerender-route-options.ts (1)
72-82: 💤 Low valueDefensive children handling looks good, but consider documenting the assumption.
The code handles
childrenas either an array or an object (viaObject.values). In current TanStack Router,route.childrenis an array, but supporting both forms is defensive and harmless. A brief comment noting why both shapes are handled (or any router-core variant that returns the object form) would help future readers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/start-plugin-core/src/prerender-route-options.ts` around lines 72 - 82, The children-handling branch in prerender-route-options.ts (the const children = route.children check and the for loop over Array.isArray(children) ? children : Object.values(children)) should include a short inline comment explaining the assumption: TanStack Router currently supplies an array but some router-core variants or legacy shapes may expose children as an object, so we defensively support both forms; reference this rationale above the children variable and mention AnyRoute/visit usage so future readers understand why we call Object.values for the object shape.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@e2e/react-start/basic/tests/prerendering.spec.ts`: - Line 99: The assertion in prerendering.spec.ts that expects the literal string "Nested prerendered slug: <!-- -->under-layout" is brittle because it depends on React's empty-comment HTML serialization; replace that expect(html).toContain(...) check with a regex-based assertion (as used on the other assertions around Line 141/142) that matches the visible text regardless of the empty-comment node (e.g., assert that html matches /Nested prerendered slug:\s*under-layout/), and apply the same change for the similar assertion at the other occurrence (the expect call containing the same comment-based string). - Around line 203-216: The test currently asserts sitemap metadata values independently which can misattribute values to the wrong <url>; update the assertions to scope them to the matching <url> block by locating the <url> node for each <loc> and then asserting its child tags (e.g., <lastmod>, <priority>, <changefreq>) match expected values. In the prerendering.spec.ts test use the sitemap string (sitemap) and either parse the XML (e.g., a lightweight XML parser) to find the <url> element whose <loc> equals the target URL and assert its children, or assert against the full expected <url> block string for each route (e.g., the block containing '<loc>https://example.com/prerender-params/hello-world</loc>') so lastmod/priority/changefreq are validated within the same <url>. In `@packages/start-client-core/src/tests/prerenderParams.test-d.ts`: - Around line 13-227: Add two type tests: one for an async prerenderParams function and one asserting per-entry sitemap typing. Create an options object whose prerenderParams is async (async () => [...]) and use it with FileBaseRouteOptions to derive Entry = Awaited<ReturnType<NonNullable<typeof options.prerenderParams>>>[number], then expectTypeOf<Entry['params']>() and expectTypeOf<Entry['sitemap']>() to match expected shapes (e.g., priority: number, changefreq: 'weekly' | ...). Also add a returned entry that includes an entry-level sitemap field to ensure per-entry sitemap is type-checked against the route-level sitemap shape. In `@packages/start-plugin-core/src/prerender-params-runner.ts`: - Around line 110-120: The current attachProcessAbortHandlers function uses process.once('SIGINT'/'SIGTERM') to call controller.abort(), which aborts the prerender controller but swallows the first signal (requiring a second Ctrl+C to terminate); update attachProcessAbortHandlers (or the call site around runPrerenderParams/prerender) to either re-emit the original signal after calling controller.abort() (e.g., restore default behavior or call process.kill(process.pid, signal) so the process will terminate on the first signal) or explicitly document this single-signal-graceful-abort behavior in the prerender/runPrerenderParams docs so users know they must press Ctrl+C twice — locate attachProcessAbortHandlers, the abort callback that calls controller.abort(), and the runPrerenderParams/prerender flow to implement the chosen change. - Around line 231-238: The mergeOptions function currently performs a shallow merge for T extends RouteSitemapOptions | RoutePrerenderOptions so nested sitemap fields (e.g. sitemap.images, sitemap.news, sitemap.alternateRefs) in override will replace those in base rather than being deep-merged; add a concise docstring above mergeOptions that states this behavior explicitly (shallow merge only, nested objects/arrays are replaced), mention the relevant types (RouteSitemapOptions, RoutePrerenderOptions) and the specific nested keys, and optionally note that tests expect this semantics so future contributors won't assume deep-merge behavior. - Around line 240-242: The current isDynamicPath function uses a simple dollar-sign presence check (function isDynamicPath(path: string) { return path.includes('$') }) which matches TanStack Router's pragmatic quick-filter behavior; leave this implementation unchanged to remain consistent with TanStack Router's intercept in interpolatePath and avoid overcomplicating with a stricter regex unless you need to handle literal unencoded '$' in paths—so keep isDynamicPath as-is (no code change). In `@packages/start-plugin-core/src/prerender-route-options.ts`: - Around line 72-82: The children-handling branch in prerender-route-options.ts (the const children = route.children check and the for loop over Array.isArray(children) ? children : Object.values(children)) should include a short inline comment explaining the assumption: TanStack Router currently supplies an array but some router-core variants or legacy shapes may expose children as an object, so we defensively support both forms; reference this rationale above the children variable and mention AnyRoute/visit usage so future readers understand why we call Object.values for the object shape. In `@packages/start-plugin-core/tests/build-sitemap.test.ts`: - Around line 147-212: The test "writes advanced sitemap metadata" for buildSitemap is missing an assertion for the <loc> element; update the test in build-sitemap.test.ts (inside the it block that calls buildSitemap and reads sitemap into the sitemap variable) to assert that the sitemap contains the canonical URL for the page path (e.g. expect(sitemap).toContain('<loc>https://example.com/news/router-launch</loc>') so the produced <loc> element for the /news/router-launch entry is validated). In `@packages/start-plugin-core/tests/prerender-params-runner.test.ts`: - Around line 4-6: Add a beforeEach hook to clear the shared logger spy so tests don't leak calls: call logger.warn.mockClear() (or vi.clearAllMocks()) in a beforeEach at the top of the test suite that contains the logger definition so logger.warn is reset before each test; this targets the logger.warn spy used in the tests (and keeps the static-route test's explicit mockClear safe to keep).
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
ea025d1a-1719-4e46-86c7-006c79ff430a📥 Commits
Reviewing files that changed from the base of the PR and between 0c80382b11af88e892d47b021c7b8266bb2620b8 and 2cba39af7551786ad3e71f0874e8376467ccde40.
📒 Files selected for processing (12)
e2e/react-start/basic/tests/prerendering.spec.tse2e/solid-start/basic/rsbuild.config.tse2e/vue-start/basic/rsbuild.config.tspackages/start-client-core/src/tests/prerenderParams.test-d.tspackages/start-plugin-core/src/post-build.tspackages/start-plugin-core/src/prerender-params-runner.tspackages/start-plugin-core/src/prerender-route-options.tspackages/start-plugin-core/src/prerender.tspackages/start-plugin-core/src/rsbuild/start-compiler-host.tspackages/start-plugin-core/tests/build-sitemap.test.tspackages/start-plugin-core/tests/prerender-params-runner.test.tspackages/start-plugin-core/tests/rsbuild-post-build.test.ts
Nit: PR description still mentions "defaults separate route-options bundling off for Nitro unless explicitly enabled" — that's no longer in the code. Worth updating so it doesn't mislead.
Trying to understand the expected behavior under Nitro v3. I smoke-tested
prerenderParamsagainstexamples/solid/start-basic-nitroon this branch with a/prerender-smoke/$idroute returning three params.The build succeeded and reported
Prerendered 25 pages, but none came fromprerenderParams— only static discovery and/postslink-crawling. The separateprerenderVite environment never built (onlyclientandssr), andprerenderParamssource survived unstripped into the deployed server bundle.Am I missing a config step, or is dynamic-params not yet wired up for Nitro? If it's a known gap, would a loud startup check (or a Nitro-specific e2e) make sense before merge so the failure mode is captured rather than silent?
@tannerlinsley yes, i didnt had time to finish this PR ( yet ), and nitro was the next check along with modules striping. but was speaking a bit with Manuel, there is still a bit of work to ensure no code ships to server and client when the pre-render is set to those routes. ( depending on the matrix of the configs, ssr: false, + prerender, etc ) . Notes to self, but to anyone, i left at investigating
pruneServerOnlySubtreesto see if could be used in a reverse way to make this work :p hope it helps !LadyBluenotes(GitHub profile, opens in a new tab) changed the title
Important
At least one additional CI pipeline execution has run since the conclusion below was written and it may no longer be applicable.
Nx Cloud is proposing a fix for your failed CI:#
We resolved a cross-device rename failure (
EXDEV) by anchoring the default.tanstack/tmpdirectory toconfigDirectoryinstead ofprocess.cwd(). The new tests introduced in this PR create aGeneratorwith its root inos.tmpdir()(/tmp/), whileprocess.cwd()points to the workspace on a separate filesystem mount, causingrename()to fail across device boundaries. With this fix, temp files are written to the same filesystem as their targets, allowing the atomic rename to succeed.Tip
✅ We verified this fix by re-running
@tanstack/start-plugin-core:test:unit,@tanstack/router-generator:test:unit.diff --git a/packages/router-generator/src/config.ts b/packages/router-generator/src/config.ts index 5c719183..283f620c 100644 --- a/packages/router-generator/src/config.ts +++ b/packages/router-generator/src/config.ts @@ -167,7 +167,18 @@ export function getConfig( } else if (process.env.TSR_TMP_DIR) { config.tmpDir = resolveTmpDir(process.env.TSR_TMP_DIR) } else { - config.tmpDir = resolveTmpDir(['.tanstack', 'tmp']) + // Resolve the default tmpDir relative to configDirectory when available so + // that temp files stay on the same filesystem as the files being written. + // Without this, a rename() across mount points (e.g. workspace → /tmp) fails + // with EXDEV: cross-device link not permitted. + if (configDirectory) { + const base = path.isAbsolute(configDirectory) + ? configDirectory + : path.resolve(process.cwd(), configDirectory) + config.tmpDir = path.resolve(base, '.tanstack', 'tmp') + } else { + config.tmpDir = resolveTmpDir(['.tanstack', 'tmp']) + } } validateConfig(config)Because this branch comes from a fork, it is not possible for us to apply fixes directly, but you can apply the changes locally using the available options below.
Apply changes locally with:
Apply fix locally with your editor ↗ View interactive diff ↗npx nx-cloud apply-locally vNi3-AtpM
🎓 Learn more about Self-Healing CI on [nx.dev](https://nx.dev/docs/features/ci-features/self-healing-ci?utm_source=pull-request&utm_medium=comment)
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
Adds typed
prerenderParamssupport and plumbing to generate dynamic prerender pages at build time, including route collection, abortable timeout-aware execution, separate route-options bundling, sitemap metadata handling, build-tool integrations (Vite/RSBuild), and expanded E2E/unit tests across React, Solid, and Vue.Changes#
Typed Dynamic Route Prerendering
packages/start-client-core/src/prerenderParams.ts,packages/start-client-core/src/tests/prerenderParams.test-d.ts,packages/start-plugin-core/src/schema.ts@tanstack/router-corewithprerenderParamsandsitemaproute options; exportsPrerenderParamsContext,PrerenderParamsEntry, sitemap/prerender option types; addsprerenderParamsTimeoutto config schema; adds type-level tests.packages/start-plugin-core/src/prerender-route-options.ts,packages/start-plugin-core/src/global.d.tscollectPrerenderRouteOptionsto traverse route trees and extractprerenderParams/sitemapmetadata; introduces global prerender route-tree typing.packages/start-plugin-core/src/prerender-params-runner.ts,packages/start-plugin-core/tests/prerender-params-runner.test.tsrunPrerenderParamswith abortable per-route timeouts, SIGINT/SIGTERM wiring, entry validation, path interpolation, search serialization, sitemap/prerender merging, deduplication, and helpers; adds comprehensive unit tests.packages/start-plugin-core/src/prerender.ts,packages/start-plugin-core/src/prerender-route-options-env.tsrunPrerenderParamswhen prerendering, and ensures cleanup of global state.packages/start-plugin-core/src/vite/planning.ts,packages/start-plugin-core/src/rsbuild/planning.ts,packages/start-plugin-core/src/rsbuild/types.ts,packages/start-plugin-core/src/vite/planning.tsseparatePrerenderRouteOptionsflag and prerender environment planning for Vite/RSBuild to produce a separate prerender route-options bundle and compute prerender output paths.packages/start-plugin-core/src/rsbuild/plugin.ts,packages/start-plugin-core/src/vite/plugin.ts,packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts,packages/start-plugin-core/src/rsbuild/start-router-plugin.ts,packages/start-plugin-core/src/rsbuild/start-compiler-host.ts,packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.tsseparatePrerenderRouteOptions, and applies code-splitting rules based on new constants.packages/start-plugin-core/src/rsbuild/post-build.ts,packages/start-plugin-core/src/rsbuild/start-compiler-host.tspackages/start-plugin-core/src/start-router-plugin/constants.ts,packages/start-plugin-core/src/start-router-plugin/constants.tsCLIENT_ROUTE_OPTION_DELETE_NODESandSERVER_ROUTE_OPTION_DELETE_NODESconstants to drive client/server option stripping (includesprerenderParamsandsitemap).packages/start-plugin-core/src/vite/prerender.ts,packages/start-plugin-core/src/vite/...packages/start-server-core/src/createStartHandler.ts,packages/start-server-core/src/global.d.tsglobalThis.TSS_PRERENDER_ROUTE_TREEduring prerender builds to allow lazy route-tree discovery from the built server entry; updates global typings.packages/start-plugin-core/src/rsbuild/virtual-modules.tspackages/start-plugin-core/src/build-sitemap.ts,packages/start-plugin-core/tests/build-sitemap.test.tsxmlns:imageandxmlns:newsnamespaces to generated sitemap and expands tests to validate advanced sitemap fields and namespaces.e2e/{react,solid,vue}-start/basic/src/routes/prerender-params.$slug.tsx,.../-prerender-params.server.ts,.../prerender-nested.$slug.tsx,.../routeTree.gen.tsprerenderParamsentries (multiple slugs, per-entry sitemap/prerender overrides, search), server-only prerender helpers, nested prerender routes, and updates generated route trees/types.e2e/{react,solid,vue}-start/basic/{rsbuild,vite}.config.ts,e2e/*/tests/prerendering.spec.ts,packages/start-plugin-core/tests/{vite-prerender,rsbuild-post-build,prerender-ssrf,prerender-routes-plugin,post-server-build,start-router-plugin-constants,...}.test.tsdocs/start/framework/{react,solid}/guide/static-prerendering.md,.changeset/tall-trees-prerender-params.mdprerenderParamsTimeout,separateRouteOptionsBundle, and a new "Dynamic Route Prerendering" section with examples; records minor bumps in changeset metadata.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~75 minutes
Possibly related PRs#
Suggested reviewers#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share