withPageAuthRequired is a higher-order component (HOC) that protects client-side pages by redirecting unauthenticated users to the login page. After login, users are automatically returned to the page they were trying to access.
This is the client-side version for React components. For server-side page protection, see withPageAuthRequired (Server).
Usage
Basic Protection
Custom Redirect Path
Custom Loading State
Custom Error Handling
Signature
Parameters
The React component to protect. The component will receive a
user prop containing the authenticated user’s profile.Configuration options for the HOC.
Return Value
Returns a wrapped React component that:- Checks if the user is authenticated using
useUser() - Redirects to login if not authenticated
- Shows the loading state while checking authentication
- Shows the error state if authentication check fails
- Renders the protected component with the
userprop if authenticated
UserProps Type
The protected component receives auser prop with the following type:
How It Works
- Authentication Check: Uses
useUser()to fetch the current user - Redirect Logic: If not authenticated, redirects to
/auth/login?returnTo=<current-page> - Return Path: After login, Auth0 redirects back to the
returnToURL - Loading State: Shows
onRedirecting()while checking authentication - Error State: Shows
onError()if the profile fetch fails
Configuration
The login endpoint can be customized using theNEXT_PUBLIC_LOGIN_ROUTE environment variable:
Examples
Complete Protected Page
With TypeScript
Pages Router Example
App Router Example
Client vs Server Protection
| Feature | Client (withPageAuthRequired) | Server (withPageAuthRequired) |
|---|---|---|
| Execution | Browser | Server |
| Redirect | Client-side navigation | Server-side redirect (302) |
| SEO | Poor (protected content not rendered) | Good (redirect before render) |
| Performance | Flash of loading state | No flash, immediate redirect |
| Use Case | Interactive client components | Static pages, SEO-important pages |
Notes
- Requires
Auth0Providerto be configured in your app - The protected component must be a client component (marked with
"use client") - The
userprop is automatically injected into your component - For server-side protection with better performance and SEO, use the server version