Overview
Route protection ensures that certain pages are only accessible to authenticated users, while others are restricted to guests. logto-authkit provides multiple patterns for implementing route protection.Protection Methods
There are three main approaches to route protection:- Middleware option in
useAuthhook (recommended) - Manual checks with conditional rendering
- Higher-order components (HOC)
Method 1: Middleware Option (Recommended)
The simplest and most declarative approach using theuseAuth hook’s built-in middleware.
Protected Route (Auth Required)
app/dashboard/page.tsx
Guest-Only Route
app/login/page.tsx
Method 2: Manual Checks
For more control over the protection logic and UI.With Loading and Redirect
With Error Message
Method 3: Higher-Order Component
Create reusable protection wrappers.Protected Page HOC
lib/withAuth.tsx
Guest-Only HOC
lib/withGuest.tsx
Advanced Patterns
Role-Based Protection
Permission-Based Protection
Conditional Component Rendering
Layout-Level Protection
app/dashboard/layout.tsx
Navigation Options
Control how redirects behave:Server-Side Protection (Next.js)
For server components and API routes:app/api/protected/route.ts
Best Practices
Use middleware option for simple cases
Use middleware option for simple cases
The
middleware option in useAuth is the simplest and most declarative way to protect routes.Always handle loading state
Always handle loading state
Show a loading indicator while
isLoadingUser is true to prevent UI flashing.Protect at the layout level when possible
Protect at the layout level when possible
For sections with multiple protected pages, protect the layout instead of each page individually.
Provide clear feedback
Provide clear feedback
When access is denied, show a clear message and provide a way to authenticate.
Use HOCs for consistent behavior
Use HOCs for consistent behavior
Create reusable HOCs to ensure consistent protection logic across your app.
Combine client and server protection
Combine client and server protection
For sensitive data, protect both the UI (client) and API routes (server).
Common Patterns Summary
Troubleshooting
The
useAuth hook waits for loading to complete before performing middleware redirects, preventing race conditions.Related
useAuth Hook
Complete hook documentation
AuthProvider
Configure authentication provider
UserCenter
Pre-built user menu component
CallbackPage
Handle authentication callbacks