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

# Add MFA to your frontend

> Build the multi-factor authentication screens in your app. Follow the full flow from sign-up to recovery with the React SDK, the JavaScript SDK, or plain GraphQL, and avoid the mistakes that lose recovery codes.

This guide shows how to build the multi-factor authentication (MFA) screens of your app. You need no previous knowledge of MFA.

Every step has three tabs: **React SDK**, **JS SDK**, and **GraphQL**. The GraphQL tab works from any language and includes `curl` and `fetch` examples. Pick one approach and follow it from top to bottom.

> [!NOTE]
>
> Turn MFA on in the console before you start. See [Multi-factor authentication](https://archie.com/docs/backend/app-services/authentication-providers/archie-auth/multi-factor-authentication.md).

## How the flow works

MFA changes what happens after a correct password. Instead of a session, the backend can answer with an error that carries a **handle**. Your app keeps the handle in memory and sends it back with the next call.

| Moment | The backend answers | Your app shows |
| - | - | - |
| First sign-in of a user without a factor, when MFA is required | `AUTH_MFA_ENROLLMENT_REQUIRED` with an `enrollToken` | The set up screen: QR code or setup key. |
| Set up finished | Ten recovery codes and a session | The recovery codes screen. |
| Later sign-ins | `AUTH_MFA_REQUIRED` with an `mfaToken` | A field for the six-digit code. |
| The user lost their phone | A recovery code answers `AUTH_MFA_ENROLLMENT_REQUIRED` with a new `enrollToken` | The set up screen again. |
| Sensitive action after five minutes | `AUTH_MFA_REAUTH_REQUIRED` | A field for a fresh code (step-up). |

Handles are not HTTP headers and not bearer tokens. They live in `errors[0].extensions` of the GraphQL response. Recognize every MFA response by `extensions.code`, never by the message text.

## Prerequisites

Check these before you write code.

1. **MFA is on.** The policy is **Optional** or **Required** for your environment.
2. **Archie Auth is enabled.** See [Getting started](https://archie.com/docs/backend/app-services/authentication-providers/archie-auth/getting-started.md).
3. **Every new user gets a role.** Set a default role for sign-ups. See [Give new users a role](#give-new-users-a-role).
4. **You have the identity API key** of your project. It looks like `anon <key>`.
5. **You can render a QR code in the browser.** For example, install the `qrcode` package. Never use an external QR service.

> [!NOTE]
>
> Frontends that Archie generates receive the identity key already configured, as `VITE_ARCHIE_IDENTITY_API_KEY`. The SDK requires the key for every call made without a session. The key ships inside your bundle by design, so it only grants access to the identity operations. Never put an admin key or a data key with write access in its place.

### Give new users a role

A user without a role can sign in, but every later call with the session fails with `INSUFFICIENT_PERMISSIONS`. The failing calls include `userMfaFactors`, `userMfaPolicy`, `authMe`, and `userMfaRegenerateRecoveryCodes`.

The recommended fix is to configure a default role for self sign-up. The Archie console does not have a field for it yet, so set it with the [Archie MCP](https://archie.com/docs/mcp/archie-mcp.md). Ask your AI assistant to update the authentication provider of type `ARCHIE_AUTH` with this configuration, using the `manage_authentication` tool with `action: update`.

```json theme={null}
{
  "selfSignupRoles": {
    "allowed": ["role-id"],
    "default": "role-id"
  }
}
```

* `allowed` lists the roles that a sign-up may request.
* `default` is the role that users get when the sign-up request names no role.

With a default role, `signUp` needs no `roleId`.

For accounts that already exist, open the **Users** tab and use **Edit roles**.

## Configure your app

Keep the connection settings in environment variables. This example uses the Vite naming.

```bash .env theme={null}
VITE_ARCHIE_API_URL=https://your-project.example.com
VITE_ARCHIE_PROJECT_ID=your-project-id
VITE_ARCHIE_ENVIRONMENT=your-environment
VITE_ARCHIE_IDENTITY_API_KEY=anon your-identity-key
```

| Setting | Used for |
| - | - |
| API URL | The base URL of your backend. The SDK adds `/graphql` for you. Without an SDK, call `<API URL>/graphql`. |
| Project ID | Sent as the `x-project-id` header. |
| Environment | Sent as the `environment` header. |
| Identity API key | Sent as the `Authorization` header on every call that has no session. |

> [tab] React SDK
>
> Create the client once and give it to `ArchieProvider`.
>
> ```tsx archie.ts theme={null}
> import { createClient } from '@archie/js-sdk';
>
> export const archie = createClient({
>   projectId: import.meta.env.VITE_ARCHIE_PROJECT_ID,
>   environment: import.meta.env.VITE_ARCHIE_ENVIRONMENT,
>   apiUrl: import.meta.env.VITE_ARCHIE_API_URL,
>   identityApiKey: import.meta.env.VITE_ARCHIE_IDENTITY_API_KEY,
> });
> ```
>
> ```tsx main.tsx theme={null}
> import { ArchieProvider } from '@archie/react-sdk';
> import { archie } from './archie';
>
> <ArchieProvider client={archie}>
>   <App />
> </ArchieProvider>;
> ```
>
> Install both packages with `npm install @archie/js-sdk @archie/react-sdk`.

> [tab] JS SDK
>
> ```ts archie.ts theme={null}
> import { createClient } from '@archie/js-sdk';
>
> export const archie = createClient({
>   projectId: import.meta.env.VITE_ARCHIE_PROJECT_ID,
>   environment: import.meta.env.VITE_ARCHIE_ENVIRONMENT,
>   apiUrl: import.meta.env.VITE_ARCHIE_API_URL,
>   identityApiKey: import.meta.env.VITE_ARCHIE_IDENTITY_API_KEY,
> });
> ```
>
> Install the package with `npm install @archie/js-sdk`.

> [tab] GraphQL
>
> Send every request as `POST` to `<API URL>/graphql` with these headers.
>
> | Header | Value |
> | - | - |
> | `Content-Type` | `application/json` |
> | `x-project-id` | Your project ID. |
> | `environment` | Your environment name. |
> | `Authorization` | `Bearer <accessToken>` when the user has a session. Otherwise your identity API key, for example `anon <key>`. |
>
> All identity operations live under `archieIdentity`.
>
> Define one small helper and reuse it in the steps below.
>
> ```ts gql.ts theme={null}
> const ENDPOINT = `${import.meta.env.VITE_ARCHIE_API_URL}/graphql`;
> const IDENTITY_KEY = import.meta.env.VITE_ARCHIE_IDENTITY_API_KEY;
>
> export class GqlError extends Error {
>   constructor(
>     message: string,
>     public code: string | undefined,
>     public extensions: Record<string, any>,
>   ) {
>     super(message);
>   }
> }
>
> // Returns data.archieIdentity. Throws GqlError with the first error of errors[].
> export async function gql<T = any>(
>   query: string,
>   variables: Record<string, unknown> = {},
>   accessToken?: string,
> ): Promise<T> {
>   const res = await fetch(ENDPOINT, {
>     method: 'POST',
>     headers: {
>       'Content-Type': 'application/json',
>       'x-project-id': import.meta.env.VITE_ARCHIE_PROJECT_ID,
>       environment: import.meta.env.VITE_ARCHIE_ENVIRONMENT,
>       Authorization: accessToken ? `Bearer ${accessToken}` : IDENTITY_KEY,
>     },
>     body: JSON.stringify({ query, variables }),
>   });
>   const body = await res.json();
>   if (body.errors?.length) {
>     const [first] = body.errors;
>     throw new GqlError(first.message, first.extensions?.code, first.extensions ?? {});
>   }
>   return body.data.archieIdentity as T;
> }
>
> // The fields every sign-in style operation returns.
> export const LOGIN_FIELDS = `
>   tokens { accessToken refreshToken expiresIn tokenType }
>   user { id email firstName lastName roles }
>   enrollRequired
>   enforceFrom
> `;
> ```
>
> The backend reports GraphQL failures with HTTP status `200` and an `errors` array. Failures of the gateway itself, such as a missing header or an invalid key, return HTTP `401` with an `errors` array that has no `extensions.code`.
>
> The `curl` examples below use these shell variables.
>
> ```bash theme={null}
> export ARCHIE_URL="https://your-project.example.com"
> export ARCHIE_PROJECT_ID="your-project-id"
> export ARCHIE_ENV="your-environment"
> export ARCHIE_IDENTITY_KEY="anon your-identity-key"
> ```

> [!NOTE]
>
> The SDK throws `IDENTITY_API_KEY_MISSING` when it makes a call without a session and `identityApiKey` is empty. Set the key. Do not work around the error with a placeholder value.

## Keep the flow state in memory

MFA needs a few short-lived values: the handles, the enrolment secret, and the recovery codes. Treat them as secrets.

* Keep them in memory only. Never write them to the URL, `localStorage`, `sessionStorage`, cookies, or logs.
* Decide which screen to show from this state. Do not rely on the order of navigation calls.

> [tab] React SDK
>
> ```tsx flow.tsx theme={null}
> import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
>
> export type Flow =
>   | { name: 'idle' }
>   | { name: 'verify'; mfaToken: string }
>   | { name: 'enroll'; enrollToken?: string }
>   // The SDK adopts the new session BEFORE confirmEnrollment resolves.
>   | { name: 'confirming' }
>   | { name: 'codes'; recoveryCodes: string[] };
>
> type FlowValue = { flow: Flow; setFlow: (next: Flow) => void };
> const FlowContext = createContext<FlowValue | null>(null);
>
> export function FlowProvider({ children }: { children: ReactNode }) {
>   const [flow, setFlow] = useState<Flow>({ name: 'idle' });
>   const value = useMemo(() => ({ flow, setFlow }), [flow]);
>   return <FlowContext.Provider value={value}>{children}</FlowContext.Provider>;
> }
>
> export function useFlow() {
>   const value = useContext(FlowContext);
>   if (!value) throw new Error('useFlow must be used inside FlowProvider');
>   return value;
> }
> ```
>
> Wrap your app with `FlowProvider`, inside `ArchieProvider`.

> [tab] JS SDK
>
> ```ts flow.ts theme={null}
> export type Flow =
>   | { name: 'idle' }
>   | { name: 'verify'; mfaToken: string }
>   | { name: 'enroll'; enrollToken?: string }
>   | { name: 'confirming' }
>   | { name: 'codes'; recoveryCodes: string[] };
>
> // A module variable is memory only. It disappears on reload, which is what you want.
> let current: Flow = { name: 'idle' };
> export const getFlow = () => current;
> export const setFlow = (next: Flow) => {
>   current = next;
> };
> ```
>
> If you use a UI framework, hold the same value in its state instead.

> [tab] GraphQL
>
> ```ts flow.ts theme={null}
> export type Flow =
>   | { name: 'idle' }
>   | { name: 'verify'; mfaToken: string }
>   | { name: 'enroll'; enrollToken?: string }
>   | { name: 'confirming' }
>   | { name: 'codes'; recoveryCodes: string[] };
>
> let current: Flow = { name: 'idle' };
> export const getFlow = () => current;
> export const setFlow = (next: Flow) => {
>   current = next;
> };
> ```
>
> You also keep the tokens of the session in memory, or in the storage your app already uses for sessions. The handles and recovery codes never go to storage.

## 1. Register the user

Registration does not return a session.

* If email verification is **off** for the environment, the user can sign in right away.
* If it is **on**, the user confirms the email with the code from the message. Then your app signs the user in or uses the session that the confirmation returns.

The new user gets the default sign-up role. See [Give new users a role](#give-new-users-a-role). You can also pass a `roleId` in the sign-up request, but it must be one of the roles in `allowed`.

> [tab] React SDK
>
> ```tsx theme={null}
> const { signUp } = useAuth();
>
> const { data, error } = await signUp({
>   email,
>   password,
>   firstName,
>   lastName,
> });
> // data = { userId: '...', message: 'User registered successfully' }
> ```
>
> `useAuth` methods never throw. Check `error` instead.

> [tab] JS SDK
>
> ```ts theme={null}
> const { userId } = await archie.auth.signUp({
>   email,
>   password,
>   firstName,
>   lastName,
> });
> ```
>
> With email verification on, finish with `archie.auth.confirmSignUp({ email, code })`. It can raise the same MFA responses as `signIn`.

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthSignupInput!) { archieIdentity { userSignUp(data: $data) { userId message } } }",
>     "variables": { "data": {
>       "email": "ada@example.com",
>       "password": "Str0ng-Passw0rd!",
>       "firstName": "Ada",
>       "lastName": "Lovelace"
>     } }
>   }'
> ```
>
> ```ts theme={null}
> import { gql } from './gql';
>
> await gql(
>   `mutation($data: AuthSignupInput!) {
>     archieIdentity { userSignUp(data: $data) { userId message } }
>   }`,
>   { data: { email, password, firstName, lastName } },
> );
> ```
>
> Response:
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userSignUp": { "userId": "00000000-0000-4000-8000-000000000001", "message": "User registered successfully" }
>     }
>   }
> }
> ```

## 2. Sign in the first time

A user who has no factor yet gets one of two results.

| MFA mode | Result |
| - | - |
| **Optional** | A normal session. Offer set up from your settings page. |
| **Required**, after the grace period | `AUTH_MFA_ENROLLMENT_REQUIRED` and an `enrollToken`. No session. |
| **Required**, during the grace period | A normal session with `enrollRequired: true` and `enforceFrom`. Send the user to set up, and call enrol without an `enrollToken`. |

> [tab] React SDK
>
> `signIn` does not report a missing second factor as an `error`. It returns an `mfa` object and keeps `error` as `null`.
>
> ```tsx theme={null}
> import { useAuth } from '@archie/react-sdk';
> import { useNavigate } from 'react-router-dom';
> import { useFlow } from './flow';
>
> function LoginForm() {
>   const { signIn } = useAuth();
>   const { setFlow } = useFlow();
>   const navigate = useNavigate();
>
>   async function onSubmit(email: string, password: string) {
>     const { session, error, mfa, enrollRequired } = await signIn({ email, password });
>
>     if (mfa?.kind === 'enroll' && mfa.enrollToken) {
>       setFlow({ name: 'enroll', enrollToken: mfa.enrollToken });
>       return navigate('/mfa/enroll');
>     }
>     if (mfa?.kind === 'verify' && mfa.mfaToken) {
>       setFlow({ name: 'verify', mfaToken: mfa.mfaToken });
>       return navigate('/mfa/verify');
>     }
>     if (mfa?.kind === 'verifyEmail') {
>       return navigate('/verify-email'); // the email must be verified before set up
>     }
>     if (error) return showError(error.message);
>
>     if (session && enrollRequired) {
>       setFlow({ name: 'enroll' }); // grace period: the session is the credential
>       return navigate('/mfa/enroll');
>     }
>     navigate('/');
>   }
>   // ...
> }
> ```

> [tab] JS SDK
>
> `signIn` throws when a second factor is involved. Recognize the error with `isMfaErrorCode`, never with `instanceof`.
>
> ```ts theme={null}
> import { isMfaErrorCode } from '@archie/js-sdk';
> import { archie } from './archie';
> import { setFlow } from './flow';
>
> export async function signIn(email: string, password: string) {
>   try {
>     const result = await archie.auth.signIn({ email, password });
>     if (result.enrollRequired) {
>       setFlow({ name: 'enroll' }); // grace period: the session is the credential
>       return 'enroll';
>     }
>     return 'home';
>   } catch (err: any) {
>     if (isMfaErrorCode(err.code)) {
>       if (err.code === 'AUTH_MFA_ENROLLMENT_REQUIRED' && err.enrollToken) {
>         setFlow({ name: 'enroll', enrollToken: err.enrollToken });
>         return 'enroll';
>       }
>       if (err.code === 'AUTH_MFA_REQUIRED' && err.mfaToken) {
>         setFlow({ name: 'verify', mfaToken: err.mfaToken });
>         return 'verify';
>       }
>     }
>     throw err; // wrong password, unverified email, service down, and so on
>   }
> }
> ```
>
> The error object also has `err.emailVerificationRequired`. When it is true, send the user through your email verification instead.

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthLoginInput!) { archieIdentity { userLogin(data: $data) { tokens { accessToken refreshToken expiresIn tokenType } user { id email firstName lastName roles } enrollRequired enforceFrom } } }",
>     "variables": { "data": { "email": "ada@example.com", "password": "Str0ng-Passw0rd!" } }
>   }'
> ```
>
> ```ts theme={null}
> import { gql, GqlError, LOGIN_FIELDS } from './gql';
> import { setFlow } from './flow';
>
> export async function signIn(email: string, password: string) {
>   try {
>     const { userLogin } = await gql(
>       `mutation($data: AuthLoginInput!) {
>         archieIdentity { userLogin(data: $data) { ${LOGIN_FIELDS} } }
>       }`,
>       { data: { email, password } },
>     );
>     keepSession(userLogin); // your own function
>     return userLogin.enrollRequired ? 'enroll' : 'home';
>   } catch (err) {
>     if (err instanceof GqlError) {
>       if (err.code === 'AUTH_MFA_ENROLLMENT_REQUIRED') {
>         setFlow({ name: 'enroll', enrollToken: err.extensions.enrollToken });
>         return 'enroll';
>       }
>       if (err.code === 'AUTH_MFA_REQUIRED') {
>         setFlow({ name: 'verify', mfaToken: err.extensions.mfaToken });
>         return 'verify';
>       }
>     }
>     throw err;
>   }
> }
> ```
>
> The first sign-in of a user who must enrol answers like this. The handle is in `extensions`, and there is no `data`.
>
> ```json theme={null}
> {
>   "errors": [
>     {
>       "message": "second factor enrolment required",
>       "path": ["archieIdentity", "userLogin"],
>       "extensions": {
>         "code": "AUTH_MFA_ENROLLMENT_REQUIRED",
>         "enforceFrom": "2026-01-01T00:00:00Z",
>         "enrollToken": "enroll-token-value"
>       }
>     }
>   ],
>   "data": null
> }
> ```

## 3. Start the set up

Ask the backend for a new authenticator secret. The response has three values.

| Field | What it is |
| - | - |
| `factorId` | Identifies the factor you are about to activate. |
| `otpauthUri` | The content of the QR code. |
| `secretBase32` | The same secret as text, for users who cannot scan. |

Let the user choose how to add the account: scan the QR code, or type the setup key. Show both options.

> [!WARNING]
>
> `otpauthUri` and `secretBase32` are secrets. Generate the QR code in the browser from `otpauthUri`. Never send the value to an external QR service. Never log it or store it.

Start the set up from a button click. If you start it from an effect, React Strict Mode runs the effect twice in development and creates two enrolments.

> [tab] React SDK
>
> ```tsx theme={null}
> import QRCode from 'qrcode';
> import { useAuth } from '@archie/react-sdk';
> import { useFlow } from './flow';
>
> type Enrollment = { factorId: string; otpauthUri: string; secretBase32: string };
>
> function EnrollScreen() {
>   const { mfa } = useAuth();
>   const { flow } = useFlow();
>   const [enrollment, setEnrollment] = useState<Enrollment | null>(null);
>   const [qr, setQr] = useState<string | null>(null);
>   const [showKey, setShowKey] = useState(false);
>
>   if (flow.name !== 'enroll' && flow.name !== 'confirming') return null;
>
>   async function start() {
>     const result = await mfa.enroll(
>       flow.name === 'enroll' && flow.enrollToken ? { enrollToken: flow.enrollToken } : undefined,
>     );
>     setEnrollment(result);
>     setQr(await QRCode.toDataURL(result.otpauthUri)); // generated in the browser
>   }
>
>   if (!enrollment) return <button onClick={start}>Set up authenticator</button>;
>
>   return (
>     <>
>       {showKey ? (
>         <code>{enrollment.secretBase32.match(/.{1,4}/g)?.join(' ')}</code>
>       ) : (
>         qr && <img src={qr} alt="QR code for your authenticator app" />
>       )}
>       <button onClick={() => setShowKey(!showKey)}>
>         {showKey ? 'Show the QR code' : 'Enter a setup key instead'}
>       </button>
>       {/* the code field comes next */}
>     </>
>   );
> }
> ```

> [tab] JS SDK
>
> ```ts theme={null}
> import QRCode from 'qrcode';
> import { archie } from './archie';
> import { getFlow } from './flow';
>
> export async function startEnrollment() {
>   const flow = getFlow();
>   const enrollToken = flow.name === 'enroll' ? flow.enrollToken : undefined;
>
>   // With an enrollToken the SDK sends it and ignores any session.
>   // Without one (grace period) the session of the user is used.
>   const { factorId, otpauthUri, secretBase32 } = await archie.auth.mfa.enroll(
>     enrollToken ? { enrollToken } : undefined,
>   );
>
>   const qrDataUrl = await QRCode.toDataURL(otpauthUri); // generated in the browser
>   const setupKey = secretBase32.match(/.{1,4}/g)!.join(' ');
>   return { factorId, qrDataUrl, setupKey }; // show one or the other; the user chooses
> }
> ```

> [tab] GraphQL
>
> Pass the `enrollToken` in the body. Without it, the call uses the session in `Authorization`.
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthMfaEnrollInput) { archieIdentity { userMfaEnroll(data: $data) { factorId otpauthUri secretBase32 } } }",
>     "variables": { "data": { "enrollToken": "enroll-token-value" } }
>   }'
> ```
>
> ```ts theme={null}
> import QRCode from 'qrcode';
> import { gql } from './gql';
>
> const { userMfaEnroll } = await gql(
>   `mutation($data: AuthMfaEnrollInput) {
>     archieIdentity { userMfaEnroll(data: $data) { factorId otpauthUri secretBase32 } }
>   }`,
>   { data: { enrollToken } },
> );
> const qrDataUrl = await QRCode.toDataURL(userMfaEnroll.otpauthUri); // in the browser
> ```
>
> Response:
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userMfaEnroll": {
>         "factorId": "00000000-0000-4000-8000-0000000000f1",
>         "otpauthUri": "otpauth://totp/Example:ada%40example.com?secret=EXAMPLESECRET&issuer=Example",
>         "secretBase32": "EXAMPLESECRET"
>       }
>     }
>   }
> }
> ```

## 4. Confirm the code and show the recovery codes

The user types the first six-digit code from the authenticator app. This proves that the app works. Only then is the factor active.

A correct code returns two things: ten **recovery codes** and a **new session**. The codes appear only once and can never be read again.

> [!WARNING]
>
> `confirmEnrollment` adopts the new session before it resolves. During that moment `isAuthenticated` is already `true`. A route guard that sends signed-in users to the home page will redirect them before they see the recovery codes, and the codes are lost. Mark the flow as `confirming` before you call the SDK, and make every guard check the flow state first. See [Common implementation mistakes](#common-implementation-mistakes).

> [tab] React SDK
>
> ```tsx theme={null}
> async function confirm(code: string, enrollment: Enrollment) {
>   const enrollToken = flow.name === 'enroll' ? flow.enrollToken : undefined;
>
>   setFlow({ name: 'confirming' }); // BEFORE the call: the session is adopted before it resolves
>   try {
>     const { recoveryCodes } = await mfa.confirmEnrollment({
>       factorId: enrollment.factorId,
>       code,
>       ...(enrollToken ? { enrollToken } : {}),
>     });
>     setFlow({ name: 'codes', recoveryCodes: [...recoveryCodes] });
>   } catch (err: any) {
>     setFlow({ name: 'enroll', enrollToken }); // the handle is still valid
>     if (err.code === 'AUTH_MFA_INVALID_CODE') return showError('That code is wrong. Try again.');
>     showError(messageForMfaError(err)); // see "Errors by code"
>   }
> }
> ```
>
> Then show the codes and wait for an explicit confirmation.
>
> ```tsx theme={null}
> function RecoveryCodesScreen() {
>   const { flow, setFlow } = useFlow();
>   const [saved, setSaved] = useState(false);
>   const navigate = useNavigate();
>   if (flow.name !== 'codes') return null;
>
>   return (
>     <>
>       <p>Save these codes now. You will not see them again.</p>
>       <ul>
>         {flow.recoveryCodes.map((c) => (
>           <li key={c}><code>{c}</code></li>
>         ))}
>       </ul>
>       <button onClick={() => navigator.clipboard.writeText(flow.recoveryCodes.join('\n'))}>
>         Copy codes
>       </button>
>       <label>
>         <input type="checkbox" checked={saved} onChange={(e) => setSaved(e.target.checked)} />
>         I saved my recovery codes
>       </label>
>       <button
>         disabled={!saved}
>         onClick={() => {
>           setFlow({ name: 'idle' }); // wipes the codes from memory
>           navigate('/');
>         }}
>       >
>         Continue
>       </button>
>     </>
>   );
> }
> ```

> [tab] JS SDK
>
> ```ts theme={null}
> import { archie } from './archie';
> import { getFlow, setFlow } from './flow';
>
> export async function confirmEnrollment(factorId: string, code: string) {
>   const flow = getFlow();
>   const enrollToken = flow.name === 'enroll' ? flow.enrollToken : undefined;
>
>   setFlow({ name: 'confirming' }); // BEFORE the call: the session is adopted before it resolves
>   try {
>     const { recoveryCodes } = await archie.auth.mfa.confirmEnrollment({
>       factorId,
>       code,
>       ...(enrollToken ? { enrollToken } : {}),
>     });
>     setFlow({ name: 'codes', recoveryCodes: [...recoveryCodes] });
>     return recoveryCodes; // render them; require an explicit "I saved them" click
>   } catch (err) {
>     setFlow({ name: 'enroll', enrollToken }); // a wrong code keeps the handle alive
>     throw err;
>   }
> }
>
> // When the user confirms that they saved the codes:
> export function acknowledgeCodes() {
>   setFlow({ name: 'idle' }); // wipes the codes from memory
> }
> ```
>
> The SDK stores the new session for you. The session from before the set up stops working.

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthMfaEnrollVerifyInput!) { archieIdentity { userMfaEnrollVerify(data: $data) { recoveryCodes session { tokens { accessToken refreshToken expiresIn tokenType } user { id email firstName lastName roles } enrollRequired enforceFrom } } } }",
>     "variables": { "data": {
>       "factorId": "00000000-0000-4000-8000-0000000000f1",
>       "code": "123456",
>       "enrollToken": "enroll-token-value"
>     } }
>   }'
> ```
>
> ```ts theme={null}
> import { gql, LOGIN_FIELDS } from './gql';
> import { setFlow } from './flow';
>
> setFlow({ name: 'confirming' });
> try {
>   const { userMfaEnrollVerify } = await gql(
>     `mutation($data: AuthMfaEnrollVerifyInput!) {
>       archieIdentity {
>         userMfaEnrollVerify(data: $data) { recoveryCodes session { ${LOGIN_FIELDS} } }
>       }
>     }`,
>     { data: { factorId, code, enrollToken } },
>   );
>   keepSession(userMfaEnrollVerify.session); // replace the old session
>   setFlow({ name: 'codes', recoveryCodes: userMfaEnrollVerify.recoveryCodes });
> } catch (err) {
>   setFlow({ name: 'enroll', enrollToken });
>   throw err;
> }
> ```
>
> Response:
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userMfaEnrollVerify": {
>         "recoveryCodes": ["aaaaa-bbbbb", "ccccc-ddddd", "...eight more codes"],
>         "session": {
>           "tokens": {
>             "accessToken": "access-token-value",
>             "refreshToken": "refresh-token-value",
>             "expiresIn": 900,
>             "tokenType": "Bearer"
>           },
>           "user": {
>             "id": "00000000-0000-4000-8000-000000000001",
>             "email": "ada@example.com",
>             "firstName": "Ada",
>             "lastName": "Lovelace",
>             "roles": ["Member"]
>           },
>           "enrollRequired": null,
>           "enforceFrom": null
>         }
>       }
>     }
>   }
> }
> ```
>
> A wrong code answers `AUTH_MFA_INVALID_CODE`. The `enrollToken` stays valid, so the user can try again.
>
> ```json theme={null}
> {
>   "errors": [
>     {
>       "message": "the verification code is not valid",
>       "path": ["archieIdentity", "userMfaEnrollVerify"],
>       "extensions": { "code": "AUTH_MFA_INVALID_CODE" }
>     }
>   ],
>   "data": null
> }
> ```

## 5. Sign in with the second factor

From now on, a correct password answers `AUTH_MFA_REQUIRED` with an `mfaToken`. Your app shows a field for the six-digit code and sends it with the token.

* The `mfaToken` lasts 5 minutes and works **once**. After a successful use, or after it expires, it answers `AUTH_MFA_TOKEN_EXPIRED`.
* A wrong code answers `AUTH_MFA_INVALID_CODE`. The token stays valid for another try.
* Do not depend on a `methods` field in the `AUTH_MFA_REQUIRED` response. It can be empty or absent. Always offer the code field and a recovery code option.

> [tab] React SDK
>
> ```tsx theme={null}
> function VerifyScreen() {
>   const { mfa } = useAuth();
>   const { flow, setFlow } = useFlow();
>   const navigate = useNavigate();
>   if (flow.name !== 'verify') return null;
>
>   async function submit(code: string) {
>     try {
>       await mfa.verify({ mfaToken: flow.mfaToken, method: 'totp', code });
>       setFlow({ name: 'idle' });
>       navigate('/');
>     } catch (err: any) {
>       switch (err.code) {
>         case 'AUTH_MFA_INVALID_CODE':
>           return showError('That code is wrong. Try again.'); // keep the handle
>         case 'AUTH_MFA_TOKEN_EXPIRED':
>           setFlow({ name: 'idle' });
>           return navigate('/login'); // start again from the password
>         case 'AUTH_MFA_LOCKED':
>           return showError(`Too many attempts. Try again after ${err.lockedUntil}.`);
>         default:
>           return showError('Verification is not available right now. Try again later.');
>       }
>     }
>   }
>   // ...
> }
> ```
>
> `useAuth()` also gives you `pendingMfa` and `verifyMfa(code, method)`. They hold the same handle inside the SDK. This guide keeps the handle in your own flow state, so every screen and guard reads one source of truth.

> [tab] JS SDK
>
> ```ts theme={null}
> import { archie } from './archie';
> import { getFlow, setFlow } from './flow';
>
> export async function verifySecondFactor(code: string) {
>   const flow = getFlow();
>   if (flow.name !== 'verify') throw new Error('No sign-in is waiting for a code');
>
>   const { session } = await archie.auth.mfa.verify({
>     mfaToken: flow.mfaToken,
>     method: 'totp',
>     code,
>   });
>   setFlow({ name: 'idle' });
>   return session; // the SDK has already stored it
> }
> ```

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthMfaVerifyInput!) { archieIdentity { userMfaVerify(data: $data) { tokens { accessToken refreshToken expiresIn tokenType } user { id email firstName lastName roles } enrollRequired enforceFrom } } }",
>     "variables": { "data": { "mfaToken": "mfa-token-value", "method": "totp", "code": "123456" } }
>   }'
> ```
>
> ```ts theme={null}
> import { gql, LOGIN_FIELDS } from './gql';
>
> const { userMfaVerify } = await gql(
>   `mutation($data: AuthMfaVerifyInput!) {
>     archieIdentity { userMfaVerify(data: $data) { ${LOGIN_FIELDS} } }
>   }`,
>   { data: { mfaToken, method: 'totp', code } },
> );
> keepSession(userMfaVerify);
> ```
>
> The password step answers like this:
>
> ```json theme={null}
> {
>   "errors": [
>     {
>       "message": "second factor required",
>       "path": ["archieIdentity", "userLogin"],
>       "extensions": { "code": "AUTH_MFA_REQUIRED", "mfaToken": "mfa-token-value" }
>     }
>   ],
>   "data": null
> }
> ```
>
> A correct code returns the same payload as a normal sign-in.
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userMfaVerify": {
>         "tokens": {
>           "accessToken": "access-token-value",
>           "refreshToken": "refresh-token-value",
>           "expiresIn": 900,
>           "tokenType": "Bearer"
>         },
>         "user": {
>           "id": "00000000-0000-4000-8000-000000000001",
>           "email": "ada@example.com",
>           "firstName": "Ada",
>           "lastName": "Lovelace",
>           "roles": ["Member"]
>         },
>         "enrollRequired": null,
>         "enforceFrom": null
>       }
>     }
>   }
> }
> ```

## 6. Recover with a recovery code

A user who lost the phone chooses "Use a recovery code" on the same screen. Send the code with `method: "recovery"`.

A recovery code **never gives a session**. The backend accepts the code and answers `AUTH_MFA_ENROLLMENT_REQUIRED` with a new `enrollToken`. The user then sets up a new authenticator.

When the user finishes that set up:

* The old authenticator stops working.
* The user gets ten new recovery codes, and the old ones stop working.
* The code the user typed is spent, even if your frontend fails afterwards.

> [tab] React SDK
>
> ```tsx theme={null}
> async function submitRecoveryCode(code: string) {
>   try {
>     await mfa.verify({ mfaToken: flow.mfaToken, method: 'recovery', code: code.trim() });
>   } catch (err: any) {
>     if (err.code === 'AUTH_MFA_ENROLLMENT_REQUIRED' && err.enrollToken) {
>       // Replace the verify handle with the enrol handle in ONE state change.
>       setFlow({ name: 'enroll', enrollToken: err.enrollToken });
>       return navigate('/mfa/enroll', { replace: true });
>     }
>     showError(messageForMfaError(err));
>   }
> }
> ```
>
> The guard of `/mfa/enroll` and the guard of `/mfa/verify` both read `flow.name`, so the order of `setFlow` and `navigate` does not matter.

> [tab] JS SDK
>
> ```ts theme={null}
> import { archie } from './archie';
> import { setFlow, getFlow } from './flow';
>
> export async function useRecoveryCode(code: string) {
>   const flow = getFlow();
>   if (flow.name !== 'verify') throw new Error('No sign-in is waiting for a code');
>
>   try {
>     await archie.auth.mfa.verify({ mfaToken: flow.mfaToken, method: 'recovery', code: code.trim() });
>   } catch (err: any) {
>     if (err.code === 'AUTH_MFA_ENROLLMENT_REQUIRED' && err.enrollToken) {
>       setFlow({ name: 'enroll', enrollToken: err.enrollToken });
>       return 'enroll'; // now run steps 3 and 4 again
>     }
>     throw err;
>   }
> }
> ```

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: $ARCHIE_IDENTITY_KEY" \
>   -d '{
>     "query": "mutation($data: AuthMfaVerifyInput!) { archieIdentity { userMfaVerify(data: $data) { tokens { accessToken } } } }",
>     "variables": { "data": { "mfaToken": "mfa-token-value", "method": "recovery", "code": "aaaaa-bbbbb" } }
>   }'
> ```
>
> ```ts theme={null}
> try {
>   await gql(
>     `mutation($data: AuthMfaVerifyInput!) {
>       archieIdentity { userMfaVerify(data: $data) { tokens { accessToken } } }
>     }`,
>     { data: { mfaToken, method: 'recovery', code } },
>   );
> } catch (err) {
>   if (err instanceof GqlError && err.code === 'AUTH_MFA_ENROLLMENT_REQUIRED') {
>     setFlow({ name: 'enroll', enrollToken: err.extensions.enrollToken });
>   }
> }
> ```
>
> Response:
>
> ```json theme={null}
> {
>   "errors": [
>     {
>       "message": "second factor enrolment required",
>       "path": ["archieIdentity", "userMfaVerify"],
>       "extensions": { "code": "AUTH_MFA_ENROLLMENT_REQUIRED", "enrollToken": "new-enroll-token-value" }
>     }
>   ],
>   "data": null
> }
> ```
>
> Now repeat steps 3 and 4 with the new `enrollToken`.

## 7. Read the policy and the factors

Use these queries to build a security settings page. Both need a session.

> [tab] React SDK
>
> ```tsx theme={null}
> const { mfa } = useAuth();
>
> const policy = await mfa.policy();
> // { mode: 'optional' | 'required' | 'off', methods: ['totp'], enforceFrom: string | null }
>
> const { factors, recoveryCodesRemaining, recoveryCodesLowWarning } = await mfa.factors();
> // factors: [{ id, type: 'totp', status: 'active', createdAt, verifiedAt, lockedUntil }]
> ```
>
> Use `recoveryCodesLowWarning` to prompt the user to regenerate the codes.

> [tab] JS SDK
>
> ```ts theme={null}
> const policy = await archie.auth.mfa.policy();
> const { factors, recoveryCodesRemaining, recoveryCodesLowWarning } = await archie.auth.mfa.factors();
> ```
>
> Remove a factor with `archie.auth.mfa.removeFactor(factorId)`. It needs a fresh second factor. See the next step.

> [tab] GraphQL
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: Bearer $ACCESS_TOKEN" \
>   -d '{ "query": "query { archieIdentity { userMfaPolicy { mode methods enforceFrom } userMfaFactors { factors { id type status createdAt verifiedAt lockedUntil } recoveryCodesRemaining recoveryCodesLowWarning } } }" }'
> ```
>
> ```ts theme={null}
> const data = await gql(
>   `query {
>     archieIdentity {
>       userMfaPolicy { mode methods enforceFrom }
>       userMfaFactors {
>         factors { id type status createdAt verifiedAt lockedUntil }
>         recoveryCodesRemaining
>         recoveryCodesLowWarning
>       }
>     }
>   }`,
>   {},
>   accessToken,
> );
> ```
>
> Responses:
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userMfaPolicy": { "mode": "required", "methods": ["totp"], "enforceFrom": "2026-01-01T00:00:00.000Z" },
>       "userMfaFactors": {
>         "factors": [
>           {
>             "id": "00000000-0000-4000-8000-0000000000f1",
>             "type": "totp",
>             "status": "active",
>             "createdAt": "2026-01-02T10:00:00.000000Z",
>             "verifiedAt": "2026-01-02T10:00:02.000000Z",
>             "lockedUntil": null
>           }
>         ],
>         "recoveryCodesRemaining": 10,
>         "recoveryCodesLowWarning": false
>       }
>     }
>   }
> }
> ```
>
> Sending these calls without any `Authorization` header answers HTTP `401` with `Missing required headers: x-project-id and/or authorization`.

## 8. Regenerate recovery codes and step up

Regenerating recovery codes, and removing a factor, are sensitive. They need a session that presented a second factor in the **last five minutes**. Otherwise the call fails with `AUTH_MFA_REAUTH_REQUIRED`.

The fix is a **step-up**. Ask the user for a fresh code, call verify **without** an `mfaToken`, and retry the original action.

* Step-up replaces the session. The previous access token stops working and answers `AUTH_TOKEN_INVALID`. Store the new tokens.
* A recovery code cannot step up a session. Only an authenticator code can.
* Regenerating makes every old recovery code stop working. Show the new codes with the same "I saved them" screen as in step 4.

> [tab] React SDK
>
> ```tsx theme={null}
> async function regenerateCodes(askForCode: () => Promise<string>) {
>   try {
>     return await mfa.regenerateRecoveryCodes();
>   } catch (err: any) {
>     if (err.code !== 'AUTH_MFA_REAUTH_REQUIRED') throw err;
>     const code = await askForCode(); // show a modal with a six-digit field
>     await mfa.stepUp({ method: 'totp', code }); // the SDK stores the new session
>     return mfa.regenerateRecoveryCodes(); // retry once
>   }
> }
> // result: { recoveryCodes: string[10], remaining: 10 }
> ```

> [tab] JS SDK
>
> ```ts theme={null}
> export async function regenerateCodes(askForCode: () => Promise<string>) {
>   try {
>     return await archie.auth.mfa.regenerateRecoveryCodes();
>   } catch (err: any) {
>     if (err.code !== 'AUTH_MFA_REAUTH_REQUIRED') throw err;
>     const code = await askForCode();
>     await archie.auth.mfa.stepUp({ method: 'totp', code });
>     return archie.auth.mfa.regenerateRecoveryCodes();
>   }
> }
> ```

> [tab] GraphQL
>
> The action fails when the second factor is older than five minutes.
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: Bearer $ACCESS_TOKEN" \
>   -d '{ "query": "mutation { archieIdentity { userMfaRegenerateRecoveryCodes { recoveryCodes remaining } } }" }'
> ```
>
> ```json theme={null}
> {
>   "errors": [
>     {
>       "message": "re-authentication is required to manage multi-factor authentication",
>       "path": ["archieIdentity", "userMfaRegenerateRecoveryCodes"],
>       "extensions": { "code": "AUTH_MFA_REAUTH_REQUIRED", "methods": ["totp"] }
>     }
>   ],
>   "data": null
> }
> ```
>
> Step up. This is `userMfaVerify` with the user's bearer token and **no** `mfaToken`.
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: Bearer $ACCESS_TOKEN" \
>   -d '{
>     "query": "mutation($data: AuthMfaVerifyInput!) { archieIdentity { userMfaVerify(data: $data) { tokens { accessToken refreshToken expiresIn tokenType } user { id email firstName lastName roles } } } }",
>     "variables": { "data": { "method": "totp", "code": "123456" } }
>   }'
> ```
>
> ```ts theme={null}
> async function regenerate(accessToken: string, askForCode: () => Promise<string>) {
>   const mutation = `mutation {
>     archieIdentity { userMfaRegenerateRecoveryCodes { recoveryCodes remaining } }
>   }`;
>   try {
>     return (await gql(mutation, {}, accessToken)).userMfaRegenerateRecoveryCodes;
>   } catch (err) {
>     if (!(err instanceof GqlError) || err.code !== 'AUTH_MFA_REAUTH_REQUIRED') throw err;
>     const code = await askForCode();
>     const { userMfaVerify } = await gql(
>       `mutation($data: AuthMfaVerifyInput!) {
>         archieIdentity { userMfaVerify(data: $data) { ${LOGIN_FIELDS} } }
>       }`,
>       { data: { method: 'totp', code } },
>       accessToken,
>     );
>     keepSession(userMfaVerify); // the old access token no longer works
>     return (await gql(mutation, {}, userMfaVerify.tokens.accessToken)).userMfaRegenerateRecoveryCodes;
>   }
> }
> ```
>
> A successful regeneration returns:
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userMfaRegenerateRecoveryCodes": { "recoveryCodes": ["aaaaa-bbbbb", "...nine more codes"], "remaining": 10 }
>     }
>   }
> }
> ```

## 9. Refresh and sign out

Access tokens last 15 minutes by default. A refresh sends the refresh token and returns a new access token and a new refresh token.

> [tab] React SDK
>
> The SDK refreshes the session automatically. Sign out with `useAuth().signOut()`.

> [tab] JS SDK
>
> The SDK refreshes the session automatically. Sign out with `archie.auth.signOut()`. You can call `archie.auth.refreshSession()` yourself.

> [tab] GraphQL
>
> The refresh call needs an `Authorization` header. A call with no header answers HTTP `401`. Send the current access token as a bearer. This was tested with a valid access token. Behavior with an expired access token is not confirmed, so if the refresh fails, send the user back to sign in.
>
> ```bash theme={null}
> curl -X POST "$ARCHIE_URL/graphql" \
>   -H "Content-Type: application/json" \
>   -H "x-project-id: $ARCHIE_PROJECT_ID" \
>   -H "environment: $ARCHIE_ENV" \
>   -H "Authorization: Bearer $ACCESS_TOKEN" \
>   -d '{
>     "query": "mutation($data: AuthRefreshInput!) { archieIdentity { userRefreshToken(data: $data) { accessToken refreshToken expiresIn tokenType } } }",
>     "variables": { "data": { "refreshToken": "refresh-token-value" } }
>   }'
> ```
>
> ```json theme={null}
> {
>   "data": {
>     "archieIdentity": {
>       "userRefreshToken": {
>         "accessToken": "new-access-token-value",
>         "refreshToken": "new-refresh-token-value",
>         "expiresIn": 900,
>         "tokenType": "Bearer"
>       }
>     }
>   }
> }
> ```
>
> The refresh token changes on every refresh. Store the new one.
>
> Sign out with the `userLogout` mutation and the bearer token. It returns `{ "message": "Logged out successfully" }`.

## Errors by code

Handle errors by `extensions.code`. In the SDKs this is `err.code`. Never match on `err.message` or on `instanceof`.

| Code | Where it appears | What to do |
| - | - | - |
| `AUTH_MFA_ENROLLMENT_REQUIRED` | Sign-in, or a recovery code | Read `enrollToken` from the error. Send the user to set up. |
| `AUTH_MFA_REQUIRED` | Sign-in | Read `mfaToken` from the error. Ask for the six-digit code. |
| `AUTH_MFA_INVALID_CODE` | Verify, confirm set up | Wrong code. Keep the handle and let the user retry. |
| `AUTH_MFA_TOKEN_EXPIRED` | Verify | The handle expired (5 minutes for `mfaToken`, 10 for `enrollToken`) or was already used. Send the user back to sign in. |
| `AUTH_MFA_LOCKED` | Verify | Too many wrong codes. Show `lockedUntil` and stop retrying. |
| `AUTH_MFA_REAUTH_REQUIRED` | Regenerate, remove factor | Run a step-up, then retry. |
| `AUTH_MFA_METHOD_NOT_ALLOWED` | Verify, step-up | The method is not allowed here. A recovery code cannot step up. |
| `AUTH_MFA_FACTOR_NOT_FOUND` | Remove factor | The factor does not exist or is not removable. Refresh the list. |
| `AUTH_MFA_NOT_ENABLED` | MFA operations | MFA is off for this environment. Hide the MFA screens. |
| `AUTH_MFA_UNAVAILABLE` | Any MFA call | The service could not answer. Do not let the user in. Ask them to try later. |
| `INSUFFICIENT_PERMISSIONS` | Any call with a session | The user has no role with access to `archieIdentity`. Assign a role. |
| `AUTH_TOKEN_INVALID` | Any call with a session | The access token is revoked. This happens after a step-up or a new enrolment. Use the newest session. |
| `AUTH_INVALID_CREDENTIALS` | Sign-in | Wrong email or password. |
| `IDENTITY_API_KEY_MISSING` | SDK, before the request | You made a call without a session and without `identityApiKey`. Set the key. |

## Common implementation mistakes

These mistakes happen in real integrations. Check your code against them.

> [accordion] The user is redirected before seeing the recovery codes
>
> `confirmEnrollment` adopts the new session before it resolves. A guard such as "signed-in users go to the home page" fires first, and the recovery codes disappear. The user can never read them again.
>
> Fix it with an explicit flow state. Set `confirming` before the call and `codes` as soon as the codes arrive. Every guard checks the flow state before it looks at `isAuthenticated`.
>
> ```tsx theme={null}
> import { Navigate } from 'react-router-dom';
> import { useAuth } from '@archie/react-sdk';
> import { useFlow } from './flow';
>
> export function RequireAuth({ children }: { children: React.ReactNode }) {
>   const { isAuthenticated, isLoading } = useAuth();
>   const { flow } = useFlow();
>
>   // The flow state wins over the session state.
>   if (flow.name === 'codes' || flow.name === 'confirming') {
>     return <Navigate to="/mfa/recovery-codes" replace />;
>   }
>   if (isLoading) return null;
>   if (!isAuthenticated) return <Navigate to="/login" replace />;
>   return <>{children}</>;
> }
>
> export function RequireEnrollFlow({ children }: { children: React.ReactNode }) {
>   const { isAuthenticated, isLoading } = useAuth();
>   const { flow } = useFlow();
>
>   if (flow.name === 'codes') return <Navigate to="/mfa/recovery-codes" replace />;
>   if (flow.name === 'confirming') return <>{children}</>; // keep the screen mounted
>   if (isLoading) return null;
>   const allowed = flow.name === 'enroll' && (flow.enrollToken || isAuthenticated);
>   return allowed ? <>{children}</> : <Navigate to="/login" replace />;
> }
> ```
>
> Use the same rule on the public routes, such as `/login`. A signed-in user who is in the `codes` state must still reach the recovery codes screen.

> [accordion] Changing the handle and navigating creates a race
>
> After a recovery code, the flow changes from `verify` to `enroll`. If you change the handle and then navigate, the guard of `/mfa/verify` can run in between. It sees no `verify` handle and sends the user to `/login`.
>
> Make guards decide from the flow state, and let each guard redirect to the screen that matches the state.
>
> ```tsx theme={null}
> export function RequireVerifyFlow({ children }: { children: React.ReactNode }) {
>   const { isAuthenticated } = useAuth();
>   const { flow } = useFlow();
>
>   if (flow.name === 'codes') return <Navigate to="/mfa/recovery-codes" replace />;
>   if (flow.name === 'enroll') return <Navigate to="/mfa/enroll" replace />; // not /login
>   if (flow.name !== 'verify') return <Navigate to={isAuthenticated ? '/' : '/login'} replace />;
>   return <>{children}</>;
> }
> ```

> [accordion] Handles, secrets, or codes end up in storage or the URL
>
> The `mfaToken`, the `enrollToken`, `otpauthUri`, `secretBase32`, and the recovery codes are credentials.
>
> * Keep them in memory only, such as React state or a module variable.
> * Never put them in the URL, query string, `localStorage`, `sessionStorage`, cookies, analytics events, or logs.
> * Generate the QR code in the browser. Never send `otpauthUri` to an external QR service.
> * Clear the flow state as soon as it is no longer needed.

> [accordion] A page reload loses the handle
>
> Memory state disappears on reload. That is correct. When the page loads with no handle and no session, send the user back to the sign-in screen. Do not try to restore a handle.
>
> Handles are short-lived anyway. The `mfaToken` lasts 5 minutes, and the `enrollToken` lasts 10 minutes. If the user waits longer, the next call answers `AUTH_MFA_TOKEN_EXPIRED`. Send the user back to sign in.

> [accordion] A recovery code is spent even when your frontend fails
>
> The backend marks a recovery code as used when it accepts it. If your app crashes, loses the response, or navigates away before the set up finishes, that code is gone.
>
> * Do not retry a recovery code automatically.
> * Take the user straight to the set up screen with the new `enrollToken`.
> * Tell users to keep the remaining codes safe.

> [accordion] Using the first session after set up
>
> Enrolment revokes the earlier sessions of the user and returns a new one. The same happens on step-up. If you keep using the old access token, calls fail with `AUTH_TOKEN_INVALID`. With an SDK, the new session is stored for you. Without an SDK, replace the stored tokens every time a response has a `session` or `tokens`.

> [accordion] Users have no role
>
> A user created without a role gets `roles: []`. Sign-in works, but every call with the session fails with `INSUFFICIENT_PERMISSIONS`. Configure a default sign-up role (see [Give new users a role](#give-new-users-a-role)), or assign a role from the **Users** tab with **Edit roles**.

## Next steps

> [card] [Multi-factor authentication](https://archie.com/docs/backend/app-services/authentication-providers/archie-auth/multi-factor-authentication.md)
>
> Modes, grace period, and account recovery.

> [card] [React SDK](https://archie.com/docs/sdk/react-sdk.md)
>
> Hooks and components for your React app.

> [card] [JavaScript SDK](https://archie.com/docs/sdk/js-sdk.md)
>
> The core client for the browser and Node.js.

> [card] [Archie Auth getting started](https://archie.com/docs/backend/app-services/authentication-providers/archie-auth/getting-started.md)
>
> Enable Archie Auth and test the basic flow.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.