Skip to main content
The Auth0Provider component wraps your application to provide optimized user data fetching and caching using SWR (Stale-While-Revalidate). It eliminates the initial loading state when using the useUser hook.

Import

Signature

Props

User
Initial user data to populate the SWR cache. This should be the authenticated user object fetched from the server.When provided, components using useUser() will immediately have access to user data without an initial loading state.
React.ReactNode
required
Your application components.

Basic Usage

Wrap your application in the root layout:
app/layout.tsx
Now all client components using useUser() will have immediate access to user data:
app/profile/page.tsx

Without Auth0Provider

Without Auth0Provider, the useUser hook will show a loading state on initial render:

With Auth0Provider

With Auth0Provider, the user data is immediately available:
app/layout.tsx
app/profile/page.tsx

Pages Router

For the Pages Router, wrap your _app.tsx:
pages/_app.tsx
Then fetch the user in getServerSideProps:
pages/index.tsx

How It Works

Auth0Provider uses SWR’s SWRConfig to populate the cache with initial user data:
This pre-populates the SWR cache with user data, eliminating the initial fetch when components call useUser().

Custom SWR Configuration

You can combine Auth0Provider with custom SWR configuration:
app/layout.tsx

Nesting Providers

Auth0Provider can be nested with other providers:
app/layout.tsx

Handling Unauthenticated Users

When there’s no authenticated user, pass undefined or omit the user prop:
app/layout.tsx
Components using useUser() will correctly show user as null:

Performance Benefits

Without Auth0Provider

  1. Client component renders
  2. useUser() initiates fetch to /auth/profile
  3. Component shows loading state
  4. Fetch completes
  5. Component re-renders with user data
Result: Flash of loading state, extra network request

With Auth0Provider

  1. Server fetches user during SSR
  2. User data passed to Auth0Provider
  3. SWR cache pre-populated
  4. Client component renders
  5. useUser() returns cached data immediately
Result: No loading state, no extra network request

TypeScript

Environment Variables

The provider uses the same profile route as useUser:
.env.local

See Also