> ## Documentation Index
> Fetch the complete documentation index at: https://thenile.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Auth

> Secure server-side user authentication

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.

<Note>
  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.
</Note>

***

## signUp

Create a new user and start a session using email/password credentials.

<CodeGroup>
  ```ts signUp theme={null}
  const user = await nile.auth.signUp({
    email: 'jane@example.com',
    password: 'secure123',
  });
  ```

  ```ts signUp raw theme={null}
  const res = await nile.auth.signUp(
    {
      email: 'jane@example.com',
      password: 'secure123',
    },
    true,
  );
  ```
</CodeGroup>

### 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`

<Note>
  On success, a session token is automatically stored via `withContext()` and
  used in subsequent calls.
</Note>

***

## signIn

Authenticate an existing user with email/password or via a configured provider.

<CodeGroup>
  ```ts credentials theme={null}
  const user = await nile.auth.signIn('email', {
    email: 'jane@example.com',
    password: 'secure123',
  });
  ```

  ```ts raw theme={null}
  const res = await nile.auth.signIn(
    'email',
    {
      email: 'jane@example.com',
      password: 'secure123',
    },
    true,
  );
  ```
</CodeGroup>

### 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`

<Note>
  This method handles both OAuth and email/password sign-in flows. For OAuth
  providers, the client should call `/api/auth/signin/{provider}`.
</Note>

***

## signOut

Ends the current session.

```ts theme={null}
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.

<Tip>
  This method is only for server-side sign out. To clear browser cookies, use
  the React SDK `<SignOutButton />` component.
</Tip>

***

## getSession

Retrieve the current user session.

```ts theme={null}
const session = await nile.auth.getSession();
```

### Returns

Either a `JWT` or an `ActiveSession` object, depending on the session type:

<CodeGroup>
  ```ts JWT theme={null}
  {
    email: string;
    sub: string;
    id: string;
    iat: number;
    exp: number;
    jti: string;
  }
  ```

  ```ts ActiveSession theme={null}
  {
    id: string;
    email: string;
    expires: string;
    user?: {
      id: string;
      name: string;
      image: string;
      email: string;
      emailVerified: void | Date;
    };
  }
  ```
</CodeGroup>

Returns `undefined` if no session is active.

***

## getCsrf

Fetches the CSRF token used for protected requests.

```ts theme={null}
const csrf = await nile.auth.getCsrf();
```

### Returns

A `csrfToken` string or a `Response` if requested

<Note>
  This method is called automatically by `signIn`, `signUp`, and
  `resetPassword`. You typically don’t need to call it manually.
</Note>

***

## listProviders

Retrieve the list of authentication providers configured for the current tenant.

```ts theme={null}
const providers = await nile.auth.listProviders();
```

### Returns

A mapping of provider names to provider configs:

```ts theme={null}
{
  [provider: string]: {
    id: string;
    name: string;
    type: string;
    signinUrl: string;
    callbackUrl: string;
  }
}
```

***

## forgotPassword

Initiate a password reset request.

```ts theme={null}
await nile.auth.forgotPassword({
  email: 'jane@example.com',
  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.

```ts theme={null}
await nile.auth.resetPassword({
  email: 'jane@example.com',
  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.

```ts theme={null}
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

<Note>
  This method is rarely used directly. It powers the internal OAuth flow of
  `signIn()`.
</Note>

***

## 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

```sh theme={null}
npm install @niledatabase/server
```

### mfa

Server entry point for `/api/auth/mfa`. HTTP verbs map automatically based on params.

<CodeGroup>
  ```ts setup theme={null}
  // Start authenticator enrollment (POST /auth/mfa)
  const setup = await nile.auth.mfa({
    scope: 'setup',
    method: 'authenticator',
  });
  ```

  ```ts verify theme={null}
  // Verify a setup or login challenge (PUT /auth/mfa)
  const verified = await nile.auth.mfa({
    token: setup.token,
    code: '123456',
    scope: setup.scope,
    method: setup.method,
  });
  ```

  ```ts remove theme={null}
  // Remove MFA (DELETE /auth/mfa)
  await nile.auth.mfa({
    method: 'authenticator',
    remove: true,
  });
  ```

  ```ts sign-in challenge theme={null}
  // Handle MFA required after sign-in
  const challenge = await nile.auth.signIn('email', {
    email: 'user@example.com',
    password: 'correct-horse',
  });

  if (challenge && typeof challenge === 'object' && 'token' in challenge) {
    await nile.auth.mfa({
      token: String((challenge as any).token),
      code: '654321',
      scope: 'challenge',
      method: (challenge as any).method ?? 'authenticator',
    });
  }
  ```
</CodeGroup>

#### 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.

```ts theme={null}
const token = parseToken(response.headers);
```

### parseCallback

Extracts the callback URL cookie from headers.

```ts theme={null}
const cbUrl = parseCallback(request.headers);
```

### parseResetToken

Extracts the reset token from password reset response.

```ts theme={null}
const resetToken = parseResetToken(response.headers);
```

<Note>
  These functions are mostly used internally. You typically don't need to
  call them directly unless customizing the authentication flow.
</Note>

\| 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.
