Repository navigation
Description
Which project does this relate to?
Start
Describe the bug
During static pre-rendering, when TanStack Start pre-renders a route, it typically calls createRootRoute's head method with loaderData twice:
- First time,
loaderDatacontains no matches - Second time,
loaderDatacontains relevant matches for the pre-rendering route
These matches are essential for making any route-specific modifications to <head>, e.g. setting the page title or other SEO metadata.
This always works for the homepage route (/) but often fails for other routes, where head(loaderData) is only called once, outputting a generic <head> and not the route-specific <head> we'd expect and leading to hydration mismatches.
Here's a reduced test case with only two routes: / and /page-1. I'm logging the loaderData.matches.map(m => m.fullPath) for every match in loaderData:
export const Route = createRootRoute({
head: (loaderData) => {
// For debugging
console.log({
urls: loaderData.matches.map((m) => m.fullPath),
});
return {
meta: [ ...$ npm run build
...
ℹ Prerendering 2 initial routes with crawler vinxi 1:43:16 PM
{ urls: [] } <<< ------ #1 head() for "/" route
{ urls: [ '/', '/' ] } <<< ------ #2 head() for "/" route
├─ / (24ms)
{ urls: [] } <<< ------ #1 head() for "page-1" route, never called again :(
├─ /page-1 (3ms)
ℹ Prerendered 2 routes in 0.405 seconds Your Example Website or App
Steps to Reproduce the Bug or Issue
- Clone down https://github.com/micah-redwood/tanstack-start-prerender-bug and
npm install
(or scaffold new TanStack Start app, add one additional route, and setup pre-rendering just like the docs recommend) - Add a
console.login thehead()method npm run buildto pre-render all routes- Notice how
head(loaderData)is called twice for the first route (/) but only once for the second route (e.g./page-1)
Expected behavior
High level, I expect head(loaderData) to be called with accurate matches for every route so I can set <head> metadata for each route separately (e.g. page title, SEO metadata, etc etc).
In the reduced test case (linked repo) it always works for the first route and always fails for the second. In the large app I'm migrating, it's much more flaky, working for about 1/3 of my routes and changing each build. Thus, it appears to be a race condition of some sort. Perhaps we're bailing on the pre-render too early before a useEffect has run or something?
Regardless, this needs fixed for TanStack Start to be a good solution for static generation. Really appreciate your help with this! I'd love to start using this at work.
Screenshots or Videos
No response
Platform
- OS: MacOS Sonoma 14.7.1
Additional context
No response
Activity
[-]createRootRoute head() sometimes only called once during pre-render[/-][+]`createRootRoute` `head()` only called once during pre-render w/out `matches`, breaking route-level `<head>` changes[/+]