Skip to main content
This guide demonstrates various patterns for protecting routes and implementing access control in your application using logto-authkit.

Basic Route Protection

The simplest way to protect a route is using the middleware option in the useAuth hook:
pages/Dashboard.tsx

Advanced Protection Patterns

Redirect authenticated users away from sign-in pages:
pages/Login.tsx

Route Guard Component

Create a reusable route guard component for cleaner code:
1

Create Route Guard Component

components/RouteGuard.tsx
2

Use Route Guard

pages/Profile.tsx

React Router Integration

Protect routes at the router level:
App.tsx

Next.js Route Protection

For Next.js applications, use client-side protection:
app/dashboard/layout.tsx

Role-Based Access Control

Implement role-based access control (RBAC):
hooks/useRBAC.ts
Use the RBAC hook in your components:
pages/AdminDashboard.tsx

Loading States

Handle loading states elegantly:
components/ProtectedPage.tsx

Best Practices

Before checking if a user exists, always verify isLoadingUser is false to avoid race conditions:
The middleware option in useAuth provides automatic redirects:
For cleaner code and better DX, implement protection at the router level rather than in each component.
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