useUser hook provides access to the authenticated user’s profile and session state in client components. It uses SWR (Stale-While-Revalidate) for efficient data fetching and caching.
Import
This hook must be used in client components (marked with
"use client" directive).Signature
Return Value
The hook returns an object with the following properties:The authenticated user object,
null if not authenticated, or undefined while loading.The User type includes:sub- User ID (subject)name- Full namenickname- Nicknamegiven_name- First namefamily_name- Last namepicture- Profile picture URLemail- Email addressemail_verified- Email verification statusorg_id- Organization ID (if logged in through an organization)- Additional custom claims
true while the user data is being fetched, false otherwise.Error object if fetching user data failed,
null otherwise.Function to manually trigger a revalidation of the user data.
Basic Usage
app/profile/page.tsx
Usage with Auth0Provider
For optimal performance, wrap your application withAuth0Provider to provide initial user data:
app/layout.tsx
Manual Revalidation
You can manually trigger a refresh of user data using theinvalidate function:
Conditional Rendering
Error Handling
Understanding SWR Behavior
TheuseUser hook uses SWR (Stale-While-Revalidate) under the hood, which provides:
- Event-driven revalidation: Data automatically revalidates when you:
- Focus the browser tab
- Reconnect to the internet
- Mount the component
- No background polling: The hook does not make continuous background requests unless explicitly configured
- Cache-first approach: Returns cached data immediately, then revalidates if needed
Customizing SWR Behavior
WhileuseUser doesn’t expose SWR configuration directly, you can control revalidation behavior globally via Auth0Provider:
app/layout.tsx
API Route
TheuseUser hook fetches data from the /auth/profile route (configurable via NEXT_PUBLIC_PROFILE_ROUTE environment variable).
If you’re using custom routes, ensure your profile endpoint returns user data:
app/api/auth/profile/route.ts
TypeScript
Custom Environment Variables
You can customize the profile API route:.env.local
See Also
- Auth0Provider - Context provider for initial user data
- withPageAuthRequired - Higher-order component for protected pages
- getSession (Server) - Server-side user access