Route Guards
Route guards allow you to protect routes by running logic before navigation occurs. Common use cases include authentication, authorization, data validation, and redirects.Overview
TanStack Router provides thebeforeLoad hook that runs before a route is loaded. Use it to:
- Check authentication status
- Verify user permissions
- Validate required context
- Redirect users to appropriate pages
- Perform side effects before rendering
Authentication Guards
Protect routes that require authentication:File-Based Routing
src/routes/_auth.tsx
src/routes/_auth/dashboard.tsx
Code-Based Routing
Setting Up Auth Context
Provide authentication state to all routes via router context:src/main.tsx
src/auth.tsx
Authorization Guards
Check user permissions and roles:src/routes/_auth/admin.tsx
Multiple Guard Conditions
Combine multiple checks:Login Route with Redirect
Capture and redirect after successful login:src/routes/login.tsx
Preloading with Guards
Guards also run during preloading:Guards run during preload, but redirects are only executed during actual navigation.
Conditional Rendering vs Guards
Use guards for navigation control, not just UI:Async Guards
Perform async operations in guards:Error Handling in Guards
Handle errors gracefully:Composing Guards
Reuse guard logic:utils/guards.ts
Best Practices
Use Redirects
Always throw redirect() instead of returning JSX from guards
Validate Async
Perform server-side validation, don’t trust client state alone
Context Over Props
Use router context for auth state, not prop drilling
Guard Hierarchies
Place guards on layout routes to protect all children
Complete Example
Here’s a full authentication setup:src/routes/__root.tsx
src/routes/_auth.tsx
Next Steps
Error Boundaries
Handle errors in protected routes
SSR
Server-side rendering with authentication