Skip to main content
The Auth module provides a comprehensive interface for managing user authentication and sessions on the server side. It wraps all interactions with the /api/auth endpoints including sign-up, sign-in, session handling, password reset, and provider management. This module is intended for use in server-side code only. For client-side login flows, use the React SDK components or OAuth redirects.
All Auth methods depend on cookies and headers for managing CSRF tokens, sessions, and callback behavior. For framework-specific integrations (e.g., Next.js), some of these flows may be automated.

signUp

Create a new user and start a session using email/password credentials.
const user = await nile.auth.signUp({
  email: '[email protected]',
  password: 'secure123',
});

Parameters

  • email: required string
  • password: required string
  • tenantId: optional. Join an existing tenant
  • newTenantName: optional. If no tenantId is provided, creates a new tenant with this name

Returns

  • A User object (with associated tenant info) or a raw Response
On success, a session token is automatically stored via withContext() and used in subsequent calls.

signIn

Authenticate an existing user with email/password or via a configured provider.
const user = await nile.auth.signIn('email', {
  email: '[email protected]',
  password: 'secure123',
});

Parameters

  • provider: either 'email' (for credentials) or another supported provider name
  • payload: either a request or credentials object
  • rawResponse: optional, when true returns a Response

Returns

  • The authenticated User object or a Response
This method handles both OAuth and email/password sign-in flows. For OAuth providers, the client should call /api/auth/signin/{provider}.

signOut

Ends the current session.
await nile.auth.signOut();

Returns

  • A Response object from /api/auth/signout
On success, the session and CSRF cookies are cleared, and nile.withContext() resets the current session state.
This method is only for server-side sign out. To clear browser cookies, use the React SDK <SignOutButton /> component.

getSession

Retrieve the current user session.
const session = await nile.auth.getSession();

Returns

Either a JWT or an ActiveSession object, depending on the session type:
{
  email: string;
  sub: string;
  id: string;
  iat: number;
  exp: number;
  jti: string;
}
Returns undefined if no session is active.

getCsrf

Fetches the CSRF token used for protected requests.
const csrf = await nile.auth.getCsrf();

Returns

A csrfToken string or a Response if requested
This method is called automatically by signIn, signUp, and resetPassword. You typically don’t need to call it manually.

listProviders

Retrieve the list of authentication providers configured for the current tenant.
const providers = await nile.auth.listProviders();

Returns

A mapping of provider names to provider configs:
{
  [provider: string]: {
    id: string;
    name: string;
    type: string;
    signinUrl: string;
    callbackUrl: string;
  }
}

forgotPassword

Initiate a password reset request.
await nile.auth.forgotPassword({
  email: '[email protected]',
  callbackUrl: 'https://myapp.com/reset-confirm',
});

Parameters

  • email: required string
  • callbackUrl: optional redirect after password reset
  • redirectUrl: optional link shown in the email

Returns

A Response with password reset instructions

resetPassword

Complete the password reset flow.
await nile.auth.resetPassword({
  email: '[email protected]',
  password: 'newPassword123',
});

Parameters

  • email, password: required
  • callbackUrl, redirectUrl: optional fallback URLs

Returns

A Response. On success, session headers are automatically applied using withContext().

callback

Handle a callback from an OAuth provider.
await nile.auth.callback('github', request);

Parameters

  • provider: name of the auth provider
  • body: a Request or serialized request body

Returns

A Response with session cookies or error headers
This method is rarely used directly. It powers the internal OAuth flow of signIn().

Multi-factor (Server)

Server-side helpers for enrolling, challenging, and removing MFA in Nile Auth.

Features

  • Single auth.mfa entry point for setup, verification, and removal against /auth/mfa
  • Works with either authenticator apps or email one-time codes
  • Reuses the server context (withContext) so CSRF, session, and callback cookies flow automatically
  • Returns parsed JSON by default while allowing raw Response access when needed
  • Redirect-friendly responses for server-rendered flows (e.g., Next.js middleware)

Installation

npm install @niledatabase/server

mfa

Server entry point for /api/auth/mfa. HTTP verbs map automatically based on params.
// Start authenticator enrollment (POST /auth/mfa)
const setup = await nile.auth.mfa({
  scope: 'setup',
  method: 'authenticator',
});

Parameters

  • token: string. MFA challenge token issued during setup or sign-in; required for scope: 'challenge'.
  • scope: 'setup' | 'challenge'. Indicates setup vs. completing a challenge. Defaults to 'challenge'.
  • method: 'authenticator' | 'email'. MFA mechanism to operate on. Defaults to 'authenticator'.
  • code: string. Verification or recovery code when completing a challenge.
  • remove: boolean. When true, sends DELETE to remove the current method. Defaults to false.
  • rawResponse: boolean. When true, returns the raw Response instead of parsed JSON.

Behavior

  • POST to initiate setup, PUT with a token to verify, and DELETE when remove is true.
  • Runs inside withNileContext, so cookies/CSRF from prior calls are reused automatically.
  • Redirects surface as { url: string } with an error query param; otherwise expect API status codes (400 invalid payload, 401 invalid code/unauthenticated, 403 token mismatch, 404 missing challenge, 410 expired challenge, 500 server error).

Response shapes

  • Authenticator setup: { method: 'authenticator'; token: string; scope: 'setup' | 'challenge'; otpauthUrl?: string; secret?: string; recoveryKeys?: string[] }
  • Email setup: { method: 'email'; token: string; scope: 'setup' | 'challenge'; maskedEmail?: string }
  • Challenge/verification: { ok: true; scope: 'setup' | 'challenge'; recoveryCodesRemaining?: number }
  • Redirects/errors: { url: string }

Tips

  • Persist and reuse the token returned from setup or sign-in for all follow-up calls.
  • For authenticated server-rendered pages, call await nile.auth.getSession() after auth.mfa so session cookies are hydrated in the current context.
  • Admin removal flows may return a challenge; route the user to MFA verification with the provided token instead of bypassing MFA.
  • Codes are typically 6 digits; recovery codes are string tokens issued during setup.

Utility Methods

These are internal helpers that power the core authentication flows:

parseToken

Extracts the session token from headers.
const token = parseToken(response.headers);

parseCallback

Extracts the callback URL cookie from headers.
const cbUrl = parseCallback(request.headers);

parseResetToken

Extracts the reset token from password reset response.
const resetToken = parseResetToken(response.headers);
These functions are mostly used internally. You typically don’t need to call them directly unless customizing the authentication flow.
| Name | Type | Default | Description | | --- | --- | --- | --- | | token | string | undefined | MFA challenge token issued during setup or sign-in; required for scope: 'challenge'. | | scope | 'setup' \| 'challenge' | 'challenge' | Indicates whether you are starting setup or completing a challenge. | | method | 'authenticator' \| 'email' | 'authenticator' | MFA mechanism to operate on. | | code | string | undefined | Verification or recovery code when completing a challenge. | | remove | boolean | false | Sends a DELETE request to remove the currently enrolled method. | | rawResponse | boolean | false | When true, skip JSON parsing and return the raw Response. | Behavior:
  • HTTP verb selection follows the API spec: POST to initiate setup, PUT with a token to verify challenges, and DELETE when remove is true. Ensure you pass the correct scope/token/remove combination so the helper sends the intended verb; if you call the HTTP API directly, use the same verbs described above.
  • The helper runs inside withNileContext, so cookies and CSRF headers from prior calls (e.g., signIn, getCsrf) are reused automatically.
  • Errors are returned as { url: string } with an error query parameter when the upstream responds with a redirect; otherwise expect HTTP status codes surfaced from the API (400 invalid payload, 401 invalid code or unauthenticated, 403 token mismatch, 404 not found, 410 expired challenge, 500 server error).

Response shapes

  • Authenticator setup: { method: 'authenticator'; token: string; scope: 'setup' \| 'challenge'; otpauthUrl?: string; secret?: string; recoveryKeys?: string[] }
  • Email setup: { method: 'email'; token: string; scope: 'setup' \| 'challenge'; maskedEmail?: string }
  • Challenge/verification: { ok: true; scope: 'setup' \| 'challenge'; recoveryCodesRemaining?: number }
  • Redirects/errors: { url: string } (inspect the error search param for the reason)

Tips

  • Always persist and reuse the token returned from setup or sign-in; it must be included on all follow-up MFA calls.
  • For authenticated server-rendered pages, call await nile.auth.getSession() after auth.mfa to ensure session cookies are hydrated in the current context.
  • When building admin tooling to disable MFA, expect a challenge response; route the user to your verification UI with the returned token instead of bypassing MFA.
  • Authenticator/email codes are expected to be 6 digits; recovery codes are string tokens issued during setup. An expired or missing challenge returns 410/404, and an invalid code returns 401.