Installation
@niledatabase/react contains components and hooks for using the API. It handles sessions, cookies, fetching data, and comes with built-in components to be used as either templates or directly in your application to handle common user tasks. It is designed to be used with @niledatabase/server, which handles API calls itself or forwards them to the regional API for your database.
Using the Auth Provider
@niledatabase/react comes with two providers, <SignedIn /> and <SignedOut /> which wrap a central <SessionProvider />. By default, they will fetch a session.
<SignedIn /> will only render children if the user is logged in. Conversely, <SignedOut /> will always render its children unless signed in.
Functions
signIn
makes aPOST request to the sign in endpoint. Expects a provider, and optional params for callbackUrl. For the cases of credentials (email + password) and email, you can opt out of redirection by passing redirect: false in the options
signOut
makes aPOST request to the sign out endpoint, with an optional params for callbackUrl to redirect the user, and redirect to leave the user on the page, but delete the session and notify the session providers the user has been logged out.
Hooks
useSession
You can obtain the current session viauseSession(). This must be called within a <SignedIn /> or <SignedOut /> provider.
useTenantId
TheuseTenantId hook manages the current tenant ID, persisting it in cookies and refetching tenant data when necessary. A tenant id is accessible via document.cookie with the name nile.tenant_id. This cookie is used by the server side SDK to make requests to the auth service.
| Value | Type | Description |
|---|---|---|
tenantId | string | undefined | The current tenant ID. |
setTenantId | (tenant: string) => void | Function to update the tenant ID. |
| Name | Type | Default | Description |
|---|---|---|---|
params | HookProps & { tenant: Tenant } | undefined | Initial tenant data. |
client | QueryClient | undefined | React Query client instance. |
- Initializes the tenant ID from
params.tenant.id, if provided. - If no tenant is found, it attempts to read from a cookie (
nile.tenant_id). - If no cookie exists, it triggers a refetch of tenants.
- Calling
setTenantId(tenantId)updates both state and cookie.
useTenants
TheuseTenants hook fetches a list of tenants from an API endpoint using React Query. It supports optional preloaded data and can be disabled to prevent automatic queries.
useQuery, which includes:
| Property | Type | Description |
|---|---|---|
data | Tenant[] | undefined | List of tenants. |
isLoading | boolean | true while fetching data. |
error | Error | null | Fetch error, if any. |
refetch | () => void | Function to manually refetch tenants. |
| Name | Type | Default | Description |
|---|---|---|---|
params | HookProps & { disableQuery?: boolean } | undefined | Hook configuration options. |
client | QueryClient | undefined | Optional React Query client instance. |
- If
disableQueryistrue, the query is disabled. - If
tenantsis provided and not empty (in the event of hydration), the query is also disabled. - Otherwise, it fetches tenants from
${baseUrl}/api/tenantsusingfetch. - The request runs only once unless manually refetched.
useEmailSignIn
TheuseEmailSignIn hook provides a mutation for signing in a user using nile auth. It allows customizing the request with callbacks and options for redirection.
| Name | Type | Default | Description |
|---|---|---|---|
onSuccess | (data: Response) => void | undefined | Callback after a successful sign-in. |
onError | (error: Error) => void | undefined | Callback if sign-in fails. |
beforeMutate | (data: any) => any | undefined | Function to modify data before mutation. |
callbackUrl | string | undefined | URL to redirect after login. |
redirect | boolean | false | Whether to redirect after login. |
- Calls
signIn('email', data)with optional modifications viabeforeMutate. - Throws an error if authentication fails.
- Redirects if
redirectistrue.
useMe
useMe is a React hook that fetches and returns the current authenticated user. It allows preloading a user via props or fetching from an API endpoint if no user is provided.
| Name | Type | Default | Description |
|---|---|---|---|
fetchUrl | string | /api/me | API endpoint to fetch the user data. |
user | User | undefined | null | undefined | Initial user data, avoids fetching if provided. |
- If a
useris passed in props, it is set immediately. - If
useris not provided, the hook fetches fromfetchUrland updates the state. - The request runs only once when the component mounts.
useResetPassword
TheuseResetPassword hook provides a way to handle password reset functionality. It sends reset requests to an authentication API and supports optional callbacks and preprocessing of request data.
| Name | Type | Default | Description |
|---|---|---|---|
params | Params | undefined | Hook configuration options. |
- Calls the API at
${baseUrl}/api/auth/reset-password(or a customfetchUrl). - Uses PUT for password updates and POST for reset requests.
- Calls
onSuccessoronErrorbased on the request outcome. - Runs a CSRF request when the hook is initialized.
- Allows modifying data before sending using
beforeMutate.
useSignUp
TheuseSignUp hook provides a way to handle user sign-up requests. It supports tenant creation, API customization, and session updates after successful registration.
| Name | Type | Default | Description |
|---|---|---|---|
params | Props | undefined | Hook configuration options. |
client | QueryClient (optional) | undefined | React Query client instance. |
- Sends a
POSTrequest to/api/signup(or a customfetchUrl). - If
createTenantistrue, assignsnewTenantNameas the user’s email. - If
createTenantis a string, it is used as the tenant name. - After a successful sign-up:
- Updates the session.
- Redirects to
callbackUrlif provided, otherwise reloads the page.
- Prefetches authentication providers and CSRF tokens on mount.
useSignIn
TheuseSignIn hook provides a simple way to authenticate users. It supports pre-processing login data before submission and handles authentication via credentials.
| Name | Type | Default | Description |
|---|---|---|---|
params | Props | undefined | Hook configuration options. |
- Sends a sign-in request using NextAuth’s
signIn('credentials', data). - If
beforeMutateis provided, it modifies the login data before the request. - Calls
onSuccessif login succeeds. - Calls
onErrorif login fails.
Multi-factor (Client)
Client-side MFA enrollment, challenge, and removal flows powered by the React SDK. TheUser object (obtained via useSession) will include a multiFactor property when MFA is enabled for the user.
Features
- Authenticator app or email one-time-code enrollment against
/auth/mfa - Recovery codes for authenticator challenges with remaining-count feedback
- Redirect-aware helpers that work with custom routers or default navigation (
ChallengeRedirect) - UI building blocks (
MultiFactor*components) plus a lightweight hook - Optional low-level
mfahelper for bespoke prompts or headless flows
Overview
Nile Auth exposes a single/auth/mfa endpoint for starting MFA setup, completing challenges, and removing an enrolled method. The React SDK wraps the endpoint in useMultiFactor and UI components that parse server responses into ready-to-render experiences.
Tokens returned from setup or sign-in responses must be echoed back on subsequent calls (challenge verification or removal). When the backend needs the browser to redirect, the helper returns { url: string } (a ChallengeRedirect) so you can route accordingly.
Installation
Quick start
Enroll with an authenticator app
Handle a challenge prompt (sign-in or removal)
API
useMultiFactor(options)
| Name | Type | Default | Description |
|---|---|---|---|
method | 'authenticator' | 'email' | (required) | MFA mechanism to enable or disable. |
currentMethod | 'authenticator' | 'email' | null | null | Currently enrolled method; blocks switching until disabled. |
onRedirect | (url: string) => void | window.location.assign | Optional handler when the backend responds with a url to visit (ChallengeRedirect). |
onChallengeRedirect | (params: { token; method; scope; destination? }) => void | Internal /mfa/prompt navigation | Override the default challenge redirect builder. |
{ setup, loading, errorType, startSetup, startDisable }.
setup:nullor an MFA payload. For authenticator:{ method: 'authenticator'; token; scope; otpauthUrl?; secret?; recoveryKeys? }. For email:{ method: 'email'; token; scope; maskedEmail? }.startSetup(): begins enrollment (POST/auth/mfa);setup.scopewill be"setup"or"challenge"if a verification step is required.startDisable(): starts removal for the given method. If verification is required,setup.scopewill be"challenge".errorType: one ofsetup,disable,parseSetup,parseDisable, ornullfor success.
Components
MultiFactorAuthenticator— renders QR code, recovery keys, and a verification form.
Props:setup: AuthenticatorSetup,onError(message: string | null),onSuccess(scope: 'setup' | 'challenge').MultiFactorEmail— shows masked email messaging and a verification form.
Props:setup: EmailSetup,onSuccess(scope: 'setup' | 'challenge').MultiFactorChallenge— shared challenge UI for either method (used for disable flows or sign-in prompts).
Props:payload: { token: string; scope: ChallengeScope; method: MfaMethod },message: string,isEnrolled: boolean,onSuccess(scope).
Error handling
- Non-200 responses are coerced into
{ url: string }(ChallengeRedirect) with anerrorsearch param.MfaVerifyFormand the examples above parse this for user-friendly messaging. - If
codeis missing or shorter than 6 digits, the React forms set a validation error before calling the API.
Additional notes
- Codes are expected to be 6 digits for authenticator/email verification; recovery codes are string tokens issued during setup.
- Challenge tokens expire; expect 410 responses for stale tokens and 404 for unknown challenges.
- Email MFA may return a
maskedEmailand require the same token on verification and disable flows.