Skip to main content

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.
It is also possible to be explicit and obtain the session server side. To do that, you would use the following:

Functions

signIn

makes a POST 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 a POST 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 via useSession(). This must be called within a <SignedIn /> or <SignedOut /> provider.

useTenantId

The useTenantId 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.
  • 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

The useTenants 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.
This hook returns the result of useQuery, which includes: Parameters
  • If disableQuery is true, the query is disabled.
  • If tenants is provided and not empty (in the event of hydration), the query is also disabled.
  • Otherwise, it fetches tenants from ${baseUrl}/api/tenants using fetch.
  • The request runs only once unless manually refetched.

useEmailSignIn

The useEmailSignIn hook provides a mutation for signing in a user using nile auth. It allows customizing the request with callbacks and options for redirection.
  • Calls signIn('email', data) with optional modifications via beforeMutate.
  • Throws an error if authentication fails.
  • Redirects if redirect is true.

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.
  • If a user is passed in props, it is set immediately.
  • If user is not provided, the hook fetches from fetchUrl and updates the state.
  • The request runs only once when the component mounts.

useResetPassword

The useResetPassword 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.
  • Calls the API at ${baseUrl}/api/auth/reset-password (or a custom fetchUrl).
  • Uses PUT for password updates and POST for reset requests.
  • Calls onSuccess or onError based on the request outcome.
  • Runs a CSRF request when the hook is initialized.
  • Allows modifying data before sending using beforeMutate.

useSignUp

The useSignUp hook provides a way to handle user sign-up requests. It supports tenant creation, API customization, and session updates after successful registration.
  • Sends a POST request to /api/signup (or a custom fetchUrl).
  • If createTenant is true, assigns newTenantName as the user’s email.
  • If createTenant is a string, it is used as the tenant name.
  • After a successful sign-up:
    • Updates the session.
    • Redirects to callbackUrl if provided, otherwise reloads the page.
  • Prefetches authentication providers and CSRF tokens on mount.

useSignIn

The useSignIn hook provides a simple way to authenticate users. It supports pre-processing login data before submission and handles authentication via credentials.

  • Sends a sign-in request using NextAuth’s signIn('credentials', data).
  • If beforeMutate is provided, it modifies the login data before the request.
  • Calls onSuccess if login succeeds.
  • Calls onError if login fails.

Multi-factor (Client)

Client-side MFA enrollment, challenge, and removal flows powered by the React SDK. The User 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 mfa helper 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)

Returns { setup, loading, errorType, startSetup, startDisable }.
  • setup: null or 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.scope will be "setup" or "challenge" if a verification step is required.
  • startDisable(): starts removal for the given method. If verification is required, setup.scope will be "challenge".
  • errorType: one of setup, disable, parseSetup, parseDisable, or null for 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 an error search param. MfaVerifyForm and the examples above parse this for user-friendly messaging.
  • If code is 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 maskedEmail and require the same token on verification and disable flows.