AuthProvider
The AuthProvider component manages authentication state on the client side using SWR for data fetching with automatic revalidation.
Setup#
Wrap your app with the AuthProvider:
Configuration#
userEndpoint#
The API endpoint to fetch user data.
Default: /api/auth/me
loginEndpoint#
The API endpoint for login requests.
Default: /api/auth/login
registerEndpoint#
The API endpoint for registration requests.
Default: /api/auth/register
logoutEndpoint#
The API endpoint for logout requests.
Default: /api/auth/logout
logoutRedirect#
Where to redirect after logout.
swrConfig#
Custom SWR configuration.
isGuestFn#
Custom function to determine if user is a guest.
parseResponse#
Custom function to parse API response and extract user data.
onLogin#
Callback when user logs in successfully.
onLogout#
Callback when user logs out.
onError#
Handle authentication errors.
initialUser#
Provide initial user data (from server-side rendering).
This prevents the loading flash on initial page load.
Full Example#
Authentication Flow#
-
Initial Load
- If
initialUseris provided, use it immediately - Otherwise, fetch from
userEndpoint isLoadingistrueduring fetch
- If
-
Revalidation
- On window focus (if enabled)
- On network reconnect (if enabled)
- On interval (if configured)
- After mutations
-
State Changes
onLogin/onLogoutcallbacks are called- Components using
useAuthre-render
Backend API Endpoint#
Your backend endpoint should return user data in this format:
Or for guests:
Protected Routes#
Use with the useAuth hook for protected pages:
TypeScript#
Custom User Type#
AuthState Type#
Peer Dependencies#
AuthProvider requires SWR as a peer dependency:
If SWR is not installed, an error will be thrown at runtime.