Chapter 18: File-Based Routing
Core Idea
File-based routing configures a TanStack Router route tree by organizing files and directories under a routes folder to mirror the application's URL structure, instead of manually writing route definitions in code.
Key Concepts
- Intuitive Organization: The file/folder layout under
routes/ mirrors the app's URL structure directly, making the route tree easy to reason about.
- Automatic Code-Splitting: Each route file is automatically split into its own chunk for performance, without manual
React.lazy wiring.
- Enhanced Type-Safety: The bundler plugin/CLI manages the type linkages (route path strings, params, search params) that would otherwise require tedious manual generic wiring.
- Directory-Based Routes: Nested folders represent nested routes, e.g.
posts/$postId.tsx for a route nested under posts/.
- Flat Routes: Dot-notation filenames represent nesting without folders, e.g.
posts.$postId.tsx is equivalent to the directory form above.
- Mixed Flat and Directory Routes: A single project can freely combine both flat and directory conventions wherever each is clearer.
- Bundler Integration: File-based routing requires configuring either the TanStack Router Plugin (Vite, Rspack/Rsbuild, Webpack, Esbuild) or the TanStack Router CLI, which generates
routeTree.gen.ts automatically on dev/build.
Key Takeaways
- File-based routing is the recommended default because it requires less code than code-based routing for equivalent functionality (see Ch 20).
- Flat (
posts.$postId.tsx) and directory (posts/$postId.tsx) conventions are interchangeable and can be mixed within the same project.
- Setting up file-based routing always requires a build-time integration (bundler plugin or CLI) that generates the route tree file; it isn't purely a runtime convention.
Connects To
- Ch 15: Routing Concepts, the naming conventions (dynamic segments, layouts, etc.) used inside route filenames.
- Ch 16: Route Trees, how these files compose into the overall tree.
- Ch 21: File Naming Conventions, the full reference for every filename prefix/suffix.
- Ch 20: Code-Based Routing, the alternative to this approach.