<AilitaProvider> and <AuthProvider> ancestors. These are already
provided if you used the standard <AilitaProvider> setup — it wraps children with both
providers automatically. useAuth provides authentication state and actions. useUser
provides profile management for the signed-in user.
useAuth
useAuth is the primary hook for authentication state and actions. It returns the current
user, authentication status, and methods to login, logout, and signup.
Return Shape
The authenticated user object.
null while loading or when not authenticated.true when the user is logged in with valid tokens.true during silent token refresh on mount and during login/logout operations.On app mount,
isLoading is true for 200–500 ms while the library attempts silent
refresh. This is why AuthGuard requires a loadingFallback — without it, the
flash-redirect anti-pattern occurs (the user sees a redirect to /login before the
refresh completes).Initiates login. Returns the full
LoginResponse for branch detection (e.g., checking
whether a challenge is required). Tokens are set automatically on a successful password
login. extraData passes additional fields (such as loginMode) to the API.Calls the server logout endpoint, then clears local tokens and auth state. Logout errors
are swallowed — local state is always cleaned up.
Initiates signup. The
app and mid fields are injected from the merchant context
automatically — you do not need to pass them.Last error message from a login, signup, or logout operation. Cleared automatically
at the start of the next attempt.
Manually clear the
error state (useful when navigating away from a form).Common Patterns
user may be null briefly during the initial silent refresh, even inside an
AuthGuard-protected route. Always use optional chaining (user?.firstName) or check
isAuthenticated first.Anti-pattern: userId from onSuccess
A common mistake is using theuserId returned by onSuccess to fetch user data
independently. This creates a redundant network request and a separate copy of user state
that can drift from what the library manages.
useUser
useUser provides methods for the authenticated user to manage their own profile, password,
email, and TOTP settings. It shares the same user object as useAuth — both read from
AuthContext, so updates are reflected everywhere immediately.
Return Shape
The same reference as
useAuth().user. Reflects the latest profile state.Loading state for profile operations (not auth loading).
true while an update,
password change, email change, or TOTP operation is in progress.Last error message from a profile operation. Cleared automatically on the next attempt.
Re-fetches
GET /users/me and updates the shared user state. Use this after external
changes or to force a sync with the server.Updates
firstName, lastName, and/or phone. Returns the updated user.The shared user state is updated automatically — all components reading
useAuth().user
or useUser().user will reflect the change without a page refresh or manual refetch.Changes the user’s password. Requires
currentPassword and newPassword. If the user
has TOTP enabled, totpCode is also required.Initiates an email address change. Returns a
challengeId that you pass to ChallengeView
to complete verification via the OTP sent to the new address.Starts TOTP setup. Returns a
qrUri to render as a QR code and backupCodes to display
to the user before they scan.Confirms TOTP setup with a 6-digit code from the authenticator app. Automatically calls
refreshProfile() — user.totpEnabled will be true after this resolves.Disables TOTP with a 6-digit verification code. Automatically calls
refreshProfile() —
user.totpEnabled will be false after this resolves.Manually clear the
error state.Profile Update Example
Password Change Example
Key Types
useSessions
useSessions fetches the authenticated user’s active sessions on mount and exposes revoke
methods. It is the hook behind the SessionsList profile component — use it directly when
you need programmatic session management rather than the prebuilt UI.
Return Shape
Array of active sessions for the current user. Each entry includes a
current: boolean
field that identifies the session belonging to this device/browser.true while the initial sessions fetch or a revoke operation is in progress.Last error message from a fetch or revoke operation.
Re-fetches
GET /users/me/sessions and updates the local sessions array.Revokes a single session by ID. Removes the session from local state on success. Throws
on error — wrap in
try/catch if you need to handle revoke failures.Revokes all sessions (except the current one, depending on backend behavior). Clears the
local sessions array on success. Throws on error.
Session Management Guide
Full useSessions usage guide including onSessionExpired contract and the complete sessions list UI example.
useMerchant
useMerchant is an admin hook for reading and updating the tenant merchant record. It is
used inside MerchantSettings — use it directly when you need to read merchant configuration
or build custom settings UI.
Return Shape
The loaded merchant record.
null while loading on mount. Contains tenant settings
including primaryColor, secondaryColor, loginMode, signupMode, and totpAllowed.true during the initial fetch and while an update call is in progress.Last error message from any operation. Clear manually with
clearError() or automatically
at the start of the next operation.Re-fetches
GET /merchants/me and updates the local merchant state.Updates the merchant record via
PATCH /merchants/:id. Returns the updated merchant.Calling
update() automatically applies the updated primaryColor and secondaryColor
to the current session via applyTheme(). You do not need to call any theme method
manually — the UI updates immediately.Generates a new API key for this merchant. Throws
'No merchant loaded' if called before
mount completes — guard with if (!merchant) return before calling.Revokes an API key by its ID. Throws
'No merchant loaded' if the merchant has not
loaded yet.Manually clear the
error state.Quick Example
useRoles
useRoles is an admin hook for managing role definitions and assigning roles to users.
It fetches all roles for the app on mount (both SYSTEM and MERCHANT roles). Use it to
build role management UI in admin dashboards.
Return Shape
All roles defined for this app — both
SYSTEM (built-in) and MERCHANT (custom) roles.true during the initial roles fetch.Last error message from a fetch operation.
Re-fetches
GET /roles and updates the local roles array.Creates a new MERCHANT-owned role and appends it to the local roles array. Returns the
created role including its generated
id.Deletes a MERCHANT-owned role and removes it from the local array.
Only MERCHANT-owned roles (
role.owner === 'MERCHANT') can be deleted. SYSTEM roles
are built-in and cannot be removed.Assigns a role to a user. Accepts an optional
expiresAt ISO 8601 string for
time-limited role grants. Does NOT update the local roles array — the role list is
app-level, not user-level.Removes a role from a user. Does NOT update the local roles array.
SYSTEM vs MERCHANT Role Hierarchy
| Owner | Description | Can be deleted | Example |
|---|---|---|---|
SYSTEM | Built-in roles defined by the ailita backend | No | ADMIN, USER |
MERCHANT | Custom roles created by your tenant | Yes, via remove() | MODERATOR, PREMIUM |
The
priority field determines role precedence when conflicts occur — lower number =
higher priority. SYSTEM roles typically have priority 1–10; assign MERCHANT roles
priorities starting at 100 to avoid conflicts.Role Checking vs Role Management
Quick Example: Assigning a Role
assign() requires app and mid values from useMerchant().merchant. Do not hardcode
these — always read them from the loaded merchant record to ensure you are assigning to
the correct tenant.Next steps
Session Management
onSessionExpired contract, useSessions full guide, and active sessions list example.
Merchant & Roles Reference
Deep-dive reference for useMerchant and useRoles with API key management and role assignment patterns.
Auth Flows
Complete login state machine and ChallengeView dual-response contract.

