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
useUser() will have immediate access to user data:
app/profile/page.tsx
Without Auth0Provider
WithoutAuth0Provider, the useUser hook will show a loading state on initial render:
With Auth0Provider
WithAuth0Provider, 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
getServerSideProps:
pages/index.tsx
How It Works
Auth0Provider uses SWR’s SWRConfig to populate the cache with initial user data:
useUser().
Custom SWR Configuration
You can combineAuth0Provider 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, passundefined or omit the user prop:
app/layout.tsx
useUser() will correctly show user as null:
Performance Benefits
Without Auth0Provider
- Client component renders
useUser()initiates fetch to/auth/profile- Component shows loading state
- Fetch completes
- Component re-renders with user data
With Auth0Provider
- Server fetches user during SSR
- User data passed to
Auth0Provider - SWR cache pre-populated
- Client component renders
useUser()returns cached data immediately
TypeScript
Environment Variables
The provider uses the same profile route asuseUser:
.env.local
See Also
- useUser - React hook for accessing user data
- getSession (Server) - Server-side user access
- SWR Documentation - Learn more about SWR