Nested Routes
Nested routes allow you to create hierarchical route structures where child routes render inside parent route layouts. This is one of the most powerful features of TanStack Router.Overview
Nested routes enable you to:- Share layouts across multiple pages
- Maintain UI state across navigation
- Create complex, hierarchical navigation structures
- Load data at multiple levels of the route tree
Basic Nested Routes
File-Based Routing
With file-based routing, nest routes using directory structure:src/routes/__root.tsx
src/routes/posts.tsx
src/routes/posts/index.tsx
src/routes/posts/$postId.tsx
Code-Based Routing
With code-based routing, usegetParentRoute and addChildren:
Pathless Layouts
Pathless layouts wrap child routes without adding a URL segment. This is useful for shared UI like authentication layouts.File-Based Routing
Use_ prefix for pathless routes:
src/routes/_auth.tsx
src/routes/_auth/dashboard.tsx
Code-Based Routing
Useid instead of path:
Multi-Level Nesting
Create deeply nested route hierarchies:src/routes/_auth/settings.tsx
Data Loading in Nested Routes
Each level of nesting can load its own data:src/routes/_auth.tsx
src/routes/_auth/dashboard.tsx
The Outlet Component
The<Outlet /> component renders child routes. Without it, child routes won’t be visible:
Parallel Routes
Render multiple route segments at the same level:Best Practices
Keep layouts focused: Each layout should handle one concern (auth, admin, public, etc.)
Good Nesting Structure
Loading States
Show pending UI while nested data loads:Next Steps
Route Guards
Protect nested routes with authentication
Error Boundaries
Handle errors in nested route hierarchies