Skip to main content
The 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
You must provide the returnTo option for Server Components since they cannot access the URL pathname.

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

Wrap getServerSideProps to protect a page:
pages/dashboard.tsx

Custom getServerSideProps

Pass your own getServerSideProps 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:
After login, users are redirected back to the original page.

Custom Login URL

Specify a custom login URL:

Conditional Redirects

Implement custom logic in getServerSideProps:

Error Handling

Handle authentication errors:

Router Comparison

Common Patterns

Role-Based Access

Organization Validation

Email Verification Check

getSession

Retrieve session data

Protect API Routes

Learn how to protect API routes