useAuth Hook
The useAuth hook provides access to authentication state and actions from any component within the AuthProvider.
Basic Usage#
Return Values#
user#
The current user object, or null if not authenticated.
isAuthenticated#
Boolean indicating if user is authenticated (non-guest).
isGuest#
Boolean indicating if current session is a guest.
isLoading#
Boolean indicating if auth state is being fetched.
error#
Error object if authentication failed.
login#
Logs in with credentials. Returns a Promise<AuthResult> ({ success, message?, user?, errors? }).
logout#
Logs out the current user and clears the session. Returns Promise<void>. To redirect after logout, set the logoutRedirect prop on AuthProvider.
mutate#
SWR mutate function to manually revalidate auth state.
register#
Registers a new user. Returns a Promise<AuthResult>. Field validation errors (if any) are available on result.errors.
refresh#
Re-fetches the current user from the backend. Returns Promise<void>.
Examples#
Navigation with Auth State#
Protected Component#
Role-Based Access#
Guest Upgrade Prompt#
Login Form#
Logout with Confirmation#
TypeScript#
Custom User Type#
Full Return Type#
useAuth() returns AuthContextValue<TUser>:
Requirements#
The useAuth hook must be used within an AuthProvider: