Capítulo 20 de 57

Chapter 20: Code-Based Routing

Core Idea

Code-based routing builds the same route tree as file-based routing but entirely in code via createRoute() and addChildren(); the docs explicitly discourage it for most apps in favor of file-based routing, though it supports every routing concept (index, dynamic, splat, layout, pathless, non-nested routes).

Key Concepts

  • createRoute({ getParentRoute, path, ... }): Manually defines a single route; requires a reference to its parent route (getParentRoute) so TypeScript can propagate type safety down the tree, mirroring what createFileRoute's path string does automatically in file-based routing.
  • createRootRoute(): Same root-route concept as file-based routing, created manually in code.
  • addChildren(): Composes parent and child route objects together to explicitly assemble the nested route tree, since there's no filesystem structure to infer it from.
  • Route Types Parity: Index routes (path: '/'), dynamic segments ($param), splat routes ($ alone), layout routes, pathless layout routes (using id instead of path), and non-nested routes (declared with the full path from root) are all supported identically to file-based routing.
  • Not Recommended: The official docs state code-based routing "is not recommended for most applications" since it requires more manual boilerplate for equivalent results to file-based routing.

Key Takeaways

  1. Default to file-based routing (Ch 18); reach for code-based routing only when filesystem-based generation genuinely doesn't fit (e.g. highly dynamic/programmatic route trees, or environments without a build step).
  2. Every concept from Ch 15 (Routing Concepts) has a direct code-based equivalent, so the mental model transfers, only the mechanism (createRoute/addChildren vs. files) changes.
  3. Pathless layout routes in code-based routing use an explicit id property instead of the file-naming _ prefix convention.

Connects To

  • Ch 15: Routing Concepts, the concepts implemented here manually.
  • Ch 16: Route Trees, lists code-based routing as one of the two tree-building methods.
  • Ch 18: File-Based Routing, the recommended alternative.