withPageAuthRequired helper protects pages by checking for an active session and redirecting unauthenticated users to the login page.
Usage
The helper works differently for App Router and Pages Router:App Router
Server Components
Wrap your Server Component to protect it:app/dashboard/page.tsx
App Router Options
string
required
The path to return to after successful authentication.
string
default:"/auth/login"
Custom login URL to redirect unauthenticated users.
Complete App Router Example
app/protected/page.tsx
Pages Router
getServerSideProps Protection
WrapgetServerSideProps to protect a page:
pages/dashboard.tsx
Custom getServerSideProps
Pass your owngetServerSideProps function:
pages/profile.tsx
Pages Router Options
string
The path to return to after authentication. Defaults to the current page.
function
Your custom
getServerSideProps function. Props are merged with the user prop.Complete Pages Router Example
pages/admin.tsx
Client-Side Protection
For Client Components, use the client-side helper:app/profile/page.tsx
The client-side helper uses the
useUser() hook and redirects to login if no user is found.Redirect Behavior
Default Redirect
Unauthenticated users are redirected to/auth/login with a returnTo parameter:
Custom Login URL
Specify a custom login URL:Conditional Redirects
Implement custom logic ingetServerSideProps:
Error Handling
Handle authentication errors:Router Comparison
Common Patterns
Role-Based Access
Organization Validation
Email Verification Check
Related Methods
getSession
Retrieve session data
Protect API Routes
Learn how to protect API routes