Basic Route Protection
The simplest way to protect a route is using themiddleware option in the useAuth hook:
pages/Dashboard.tsx
Advanced Protection Patterns
- Guest-Only Routes
- Conditional Protection
Redirect authenticated users away from sign-in pages:
pages/Login.tsx
Route Guard Component
Create a reusable route guard component for cleaner code:React Router Integration
Protect routes at the router level:App.tsx
Next.js Route Protection
For Next.js applications, use client-side protection:- App Router
- Pages Router
app/dashboard/layout.tsx
Role-Based Access Control
Implement role-based access control (RBAC):hooks/useRBAC.ts
pages/AdminDashboard.tsx
Loading States
Handle loading states elegantly:components/ProtectedPage.tsx
Best Practices
Always check loading state
Always check loading state
Before checking if a user exists, always verify
isLoadingUser is false to avoid race conditions:Use middleware option for automatic redirects
Use middleware option for automatic redirects
The
middleware option in useAuth provides automatic redirects:Implement route guards at the router level
Implement route guards at the router level
For cleaner code and better DX, implement protection at the router level rather than in each component.
Provide clear feedback during loading
Provide clear feedback during loading
Always show loading indicators while authentication state is being determined:
Next Steps
React SPA Example
See a complete React application
Next.js Example
Explore Next.js integration
useAuth Hook
Learn more about the useAuth hook
Server auth
Implement server-side protection