withPageAuthRequired higher-order component (HOC) protects client-side rendered pages by automatically redirecting unauthenticated users to the login page.
Import
This is the client-side version of
withPageAuthRequired. For server-side page protection, see withPageAuthRequired (Server).Signature
Parameters
ComponentType<P & UserProps>
required
The component to protect. The wrapped component will receive a
user prop containing the authenticated user object.WithPageAuthRequiredOptions
Configuration options for the HOC.
string
The path to return the user to after login. If not specified, the user will be returned to the current page.
() => JSX.Element
Custom component to render while redirecting to login. Defaults to an empty fragment.
(error: Error) => JSX.Element
Custom component to render when there’s an error fetching user data. Defaults to an empty fragment.
Return Value
Returns a new React functional component that:- Checks for user authentication
- Redirects to login if not authenticated
- Passes the
userprop to the wrapped component - Handles loading and error states
Basic Usage
app/dashboard/page.tsx
Custom Return Path
Specify where to redirect after login:Custom Loading State
Show a custom component while redirecting to login:Custom Error Handling
Handle errors when fetching user data:Complete Example
With TypeScript
Passing Additional Props
How It Works
The HOC performs the following steps:- Uses
useUserhook to fetch user data - Checks authentication state:
- If
isLoadingistrue, rendersonRedirectingcomponent - If
errorexists, rendersonErrorcomponent - If no
userand not loading, redirects to login
- If
- Constructs login URL with
returnToparameter - Redirects using
window.location.assign() - Passes
userprop to wrapped component once authenticated
Redirect Flow
When an unauthenticated user visits a protected page:- User visits
/dashboard withPageAuthRequireddetects no user- Redirects to
/auth/login?returnTo=/dashboard - User completes authentication
- Auth0 redirects back to
/dashboard - User sees the protected content
Client vs Server Protection
When to Use Client Protection
- Client-side rendered (CSR) pages
- Pages with heavy client-side interactions
- Single-page application (SPA) patterns
- When you need custom loading/error states
When to Use Server Protection
Use the server-side version for:- Server-side rendered (SSR) pages
- Better SEO
- Faster initial page loads
- No flash of unauthenticated content
Environment Variables
The HOC uses the login route for redirects:.env.local
Common Patterns
Role-Based Access Control
Organization Check
See Also
- withPageAuthRequired (Server) - Server-side page protection
- useUser - Access user data in components
- withApiAuthRequired - Protect API routes