Code-Based Routing
Code-based routing gives you complete programmatic control over your route tree. While file-based routing is recommended for most applications, code-based routing is useful for dynamic route generation, migration from other routers, or specific architectural requirements.Overview
With code-based routing, you manually define routes using thecreateRoute and createRootRoute functions, then compose them into a route tree.
Basic Setup
1
Install TanStack Router
2
Create the Root Route
Every router needs a root route:
3
Create Child Routes
Define your application routes:
4
Build the Route Tree
Compose routes into a tree:
5
Create and Register the Router
Complete Example
Here’s a full example from the TanStack Router source:src/main.tsx
Route Configuration Options
Path Parameters
Define dynamic route segments with$ prefix:
Pathless Routes
Create layout routes without adding path segments:Data Loading
Load data before rendering:Error Handling
Customize error and not found components:Advanced Patterns
Nested Route Trees
Build complex hierarchies:Route Guards
Protect routes withbeforeLoad:
Lazy Loading Routes
Split code with.lazy():
Router Configuration
Customize router behavior:Type Safety
Register your router for full type safety:- Type-safe route paths in
Linkandnavigate - Type-safe params and search params
- Type-safe loader data
- Autocomplete for routes throughout your app
When to Use Code-Based Routing
Dynamic Routes
Generate routes programmatically based on configuration or API data
Migration
Easier migration path from other routers like React Router or Next.js
Monorepos
Share routes across multiple applications in a monorepo
Fine Control
Need precise control over route composition and organization
Recommendation: For most applications, file-based routing provides better DX and is easier to maintain. Use code-based routing when you have specific requirements that file-based routing can’t satisfy.
Next Steps
File-Based Routing
Learn about the recommended file-based approach
Code Splitting
Optimize your bundle with lazy loading