File-Based Routing
TanStack Router supports file-based routing, which automatically generates your route tree from your file system structure. This approach provides excellent developer experience with type safety and automatic route generation.Overview
File-based routing eliminates the need to manually define routes by deriving them from your file structure. The router automatically generates type-safe routes based on your file naming conventions.Setup
1
Install the Router Plugin
Install the TanStack Router plugin for your bundler:
2
Configure Your Bundler
Add the plugin to your bundler configuration:
3
Create Your Routes Directory
Create a
src/routes/ directory for your route files:4
Create the Root Route
Every file-based router needs a root route. Create
src/routes/__root.tsx:src/routes/__root.tsx
5
Create Route Files
Create route files following the naming conventions:
src/routes/index.tsx
6
Import and Use the Generated Route Tree
The plugin automatically generates a
routeTree.gen.ts file. Import it in your main file:src/main.tsx
File Naming Conventions
Index Routes
Files namedindex.tsx create index routes:
Dynamic Route Segments
Use$ prefix for dynamic parameters:
src/routes/posts/$postId.tsx
Layout Routes
Files ending in.route.tsx or without a component create layouts:
src/routes/posts.route.tsx
Pathless Layouts
Use_ prefix for routes that don’t add a path segment:
src/routes/_layout.tsx
Splat/Catch-All Routes
Use$.tsx for catch-all routes:
Route Configuration
File-based routes support all the same options as code-based routes:src/routes/posts/$postId.tsx
Plugin Configuration
Customize the plugin behavior:vite.config.ts
Benefits of File-Based Routing
Type Safety
Automatic type generation for all routes, params, and search params
Developer Experience
No manual route configuration - just create files and they work
Code Splitting
Automatic code splitting based on your file structure
Conventions
Clear, standard conventions for organizing your routes
Best Practices
Co-locate related files: Keep components, hooks, and utilities close to the routes that use them.
Next Steps
Nested Routes
Learn how to create nested route hierarchies
Route Guards
Protect routes with authentication and authorization