Routes
Routes are the building blocks of TanStack Router. Each route represents a URL pattern and defines what should happen when that URL is matched - including what to load, what to render, and how to handle errors.Route Definition
Routes are defined using thecreateRoute or createFileRoute functions from the router package.
Code-Based Routes
File-Based Routes
getParentRoute - the parent is inferred from the file path.
Route Options
Routes accept a comprehensive set of options to control their behavior.Path and Identification
- A
path- Creates a routable URL segment - An
id- Creates a layout/wrapper route with no URL segment
Component Options
Define what renders at different states:All component options support lazy loading. Use the
lazy method to code-split components.Path Parameters
Path parameters capture dynamic segments from the URL.Basic Parameters
packages/router-core/src/route.ts:169-172, parameters are typed based on the path pattern:
Parsing Parameters
Transform and validate parameters:Optional Parameters
Make parameters optional with the{- syntax:
Search Parameter Validation
Validate and type search parameters using any validation library:With Zod
Manual Validation
validateSearch option is defined in packages/router-core/src/route.ts:928.
Route Context
Provide data to child routes via context:Lifecycle Hooks
Routes have several lifecycle hooks that run at different times.beforeLoad
Runs before the route loads. Perfect for authentication checks:packages/router-core/src/route.ts:969-993, beforeLoad receives:
context- Accumulated context from parent routeslocation- Current location objectparams- Path parameterssearch- Validated search parametersabortController- Signal for cancellation
Context Function
Provides synchronous context to the route:Loading States
Control how loading states are displayed:Error Handling
Handle errors at the route level:Code Splitting
Lazy load route components and loaders:Stale Time and Caching
Control when route data is considered fresh:Best Practices
Use beforeLoad for authentication
Use beforeLoad for authentication
The
beforeLoad hook is perfect for auth checks because it runs before the loader, preventing unnecessary data fetching for unauthorized users.Validate search params with schemas
Validate search params with schemas
Always validate search parameters with a schema library like Zod. This provides type safety and runtime validation in one step.
Code split heavy components
Code split heavy components
Use the
lazy method to split large components. This reduces initial bundle size and improves performance.Provide meaningful error boundaries
Provide meaningful error boundaries
Every route should have an
errorComponent to gracefully handle failures and provide recovery options.Next Steps
Loaders
Learn how to load data for your routes
Navigation
Discover navigation patterns and APIs
Type Safety
Master type-safe routing patterns
Search Params
Deep dive into search parameter handling