Skip to main content
The 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 user prop 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:
  1. Uses useUser hook to fetch user data
  2. Checks authentication state:
    • If isLoading is true, renders onRedirecting component
    • If error exists, renders onError component
    • If no user and not loading, redirects to login
  3. Constructs login URL with returnTo parameter
  4. Redirects using window.location.assign()
  5. Passes user prop to wrapped component once authenticated

Redirect Flow

When an unauthenticated user visits a protected page:
  1. User visits /dashboard
  2. withPageAuthRequired detects no user
  3. Redirects to /auth/login?returnTo=/dashboard
  4. User completes authentication
  5. Auth0 redirects back to /dashboard
  6. 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