Capítulo 41 de 57

Chapter 41: Document Head Management

Core Idea

TanStack Router provides built-in, composable control over the document <head> (title, meta, link, script tags) via the routeOptions.head property, with automatic deduping and merging across nested routes, for both TanStack Start full-stack apps and plain single-page applications.

Key Concepts

  • routeOptions.head: a route option returning an object with title, meta, links, styles, and scripts properties, defining the head tags a route contributes.
  • <HeadContent />: component that must be rendered, ideally within the <head> tag of the root layout (or as high as possible in the tree), to actually output the collected head tags.
  • <Scripts />: component rendered in the <body> tag for scripts that need DOM access before hydration.
  • Automatic deduping: title and meta tags are deduped automatically; nested routes' tags merge composably, with later (more specific/child) occurrences overriding parent ones. meta tags are matched and replaced by name or property.
  • Automatic loading/unloading: head tags are added and removed automatically based on whether their route is currently matched/visible.
  • ScriptOnce: a component for running a script once during SSR (e.g. to prevent theme flicker or unstyled content flash) before React hydration; it removes itself from the DOM on subsequent client-side navigations.

Key Takeaways

  1. Always render both <HeadContent /> (in <head>) and <Scripts /> (in <body>) at the root layout to get head management and script injection working.
  2. Child route head definitions override parent definitions for the same title or matching meta tag, no manual deduping needed.
  3. Use ScriptOnce specifically for pre-hydration DOM scripts like theme initialization, not for general scripts (use head.scripts or <Scripts /> instead).

Connects To

  • Ch 42: SSR, since document head rendering interacts directly with server-rendered markup and hydration timing.