Overview
With code-based routing, you create routes using thecreateRoute API and compose them into a route tree. Benefits include:
- Explicit configuration - Full visibility into your route structure
- Runtime flexibility - Conditionally create routes based on runtime logic
- No build step - Works without bundler plugins
- Type safety - Full TypeScript support
Basic setup
1
Create the root route
Every router needs a root route:
src/routes.tsx
2
Create child routes
Define individual routes with
createRoute:src/routes.tsx
3
Build the route tree
Combine routes into a tree structure:
src/routes.tsx
4
Create the router
Initialize the router with your route tree:
src/main.tsx
Route configuration
Data loading
Define loaders to fetch data before rendering:Search params validation
Validate and type search parameters:Nested routes
Create layout routes with children:Lazy loading
Split routes for code splitting:src/routes/posts.lazy.tsx
Error handling
Define error boundaries:Path parameters
Define dynamic segments:Type registration
Register your router for global type safety:Type registration enables autocomplete and type checking throughout your application.
Best practices
Organize routes by feature
Organize routes by feature
Group related routes together to keep your route tree maintainable.
Use lazy loading for large routes
Use lazy loading for large routes
Split heavy components to reduce initial bundle size.
Validate search params
Validate search params
Always validate search params for type safety and runtime correctness.
Next steps
File-based routing
Explore automatic route generation
Data loading
Learn advanced data loading patterns