Skip to main content

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:
  1. Middleware option in useAuth hook (recommended)
  2. Manual checks with conditional rendering
  3. Higher-order components (HOC)
The simplest and most declarative approach using the useAuth 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
Control how redirects behave:

Server-Side Protection (Next.js)

For server components and API routes:
app/api/protected/route.ts

Best Practices

The middleware option in useAuth is the simplest and most declarative way to protect routes.
Show a loading indicator while isLoadingUser is true to prevent UI flashing.
For sections with multiple protected pages, protect the layout instead of each page individually.
When access is denied, show a clear message and provide a way to authenticate.
Create reusable HOCs to ensure consistent protection logic across your app.
For sensitive data, protect both the UI (client) and API routes (server).

Common Patterns Summary

Troubleshooting

Infinite redirect loop: Ensure redirectTo and redirectIfAuthenticated point to pages with different middleware settings.
Flash of unauthenticated content: Always check isLoadingUser before rendering protected content.
The useAuth hook waits for loading to complete before performing middleware redirects, preventing race conditions.

useAuth Hook

Complete hook documentation

AuthProvider

Configure authentication provider

UserCenter

Pre-built user menu component

CallbackPage

Handle authentication callbacks