Overview
TheuseAuth hook provides access to the current user’s authentication state and authentication methods. It also supports middleware for route protection and automatic redirects.
Installation
Basic Usage
Parameters
The hook accepts an optionaloptions object:
Configuration object for authentication behavior and route protection.
Return Value
The hook returns anAuthContextType object:
Current authenticated user object, or
null if not authenticated.Loading state indicator.
true while fetching user data, false when complete.Function to initiate sign-in flow. -
callbackUrl: Optional URL to redirect to after authentication - usePopup: Override the
enablePopupSignIn setting from AuthProvider tsx // Default sign-in await signIn() // With custom callback URL await signIn('/dashboard') // Force popup mode await signIn('/callback', true) // Force redirect mode await signIn('/callback', false) Function to sign out the current user.
callbackUrl: Optional URL to redirect to after sign-outglobal: Whether to perform global sign-out (default:true)
Function to manually refresh the authentication state.
tsx // Refresh user data await refreshAuth() Whether popup sign-in is enabled (from
AuthProvider configuration).Examples
Display User Information
Protected Page
Guest-Only Page
Custom Sign-In Button
Sign-Out with Confirmation
Conditional Rendering
Manual Auth Refresh
With Loading State
Middleware Behavior
middleware: 'auth'
Protects routes that require authentication:
middleware: 'guest'
Protects routes that should only be accessible to unauthenticated users:
No Middleware
SSR Considerations
The hook waits for client-side mounting and
isLoadingUser to be false before performing middleware redirects, preventing hydration
mismatches.Best Practices
Use middleware for route protection
Use middleware for route protection
Instead of manually checking
user and redirecting, use the built-in middleware option for cleaner code.Always check loading state
Always check loading state
Always handle the
isLoadingUser state to prevent UI flashing and provide better UX.Memoize options object
Memoize options object
The hook internally memoizes options, but you can also wrap your options in
useMemo if they depend on other state.Handle sign-out errors
Handle sign-out errors
Wrap
signOut calls in try-catch blocks to handle potential errors gracefully.TypeScript Support
The hook is fully typed:Troubleshooting
The hook automatically refreshes auth state when: - Window regains focus - Storage events occur (cross-tab sync) - Custom
auth-state-changed events are dispatchedRelated
AuthProvider
Configure authentication provider
Route Protection
Advanced route protection patterns
UserCenter
Pre-built user menu component
CallbackPage
Handle authentication callbacks