Capítulo 22 de 57

Chapter 22: URL Rewrites

Core Idea

URL rewrites let TanStack Router present a different URL to the browser than the one it uses internally for matching, enabling i18n locale prefixes, subdomain routing, legacy URL migration, and multi-tenant domains without polluting route definitions.

Key Concepts

  • Input Rewrite: Transforms the browser's URL into the router's internal URL before route matching happens.
  • Output Rewrite: Transforms the router's internal URL into the URL displayed in the browser.
  • location.href: The internal URL used by the router (after the input rewrite has been applied).
  • location.publicHref: The external URL actually shown in the browser (after the output rewrite has been applied).
  • Rewrite Functions: Configured at router creation; input/output functions receive a URL object and can mutate and return it, return a new URL instance, return a full href string (parsed into a URL), or return undefined to skip the rewrite for that URL.
  • composeRewrites: Combines multiple rewrites; input transformations run in sequence, output transformations run in reverse sequence, so rewrites compose predictably in both directions.
  • basepath Integration: Rewrites automatically compose with the router's basepath configuration, maintaining correct ordering between the two.

Key Takeaways

  1. Use input/output rewrites (not route path hacks) for URL concerns that are orthogonal to your route tree, such as locale prefixes, tenant subdomains, or legacy redirects, keeping route definitions clean.
  2. location.href (internal) and location.publicHref (external/browser-facing) are the two different URL views a rewritten router exposes; use the right one depending on whether you need the router's matching view or what the user actually sees.
  3. When combining multiple rewrites via composeRewrites, remember output rewrites apply in reverse order relative to input rewrites, this matters when rewrites depend on each other's transformations.

Connects To

  • Ch 23: Navigation, since the URLs produced during navigation are subject to these rewrites.
  • Ch 31: History Types, related low-level URL/history handling.