Skip to main content
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.
Turn MFA on in the console before you start. See Multi-factor authentication.

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. 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.
  3. Every new user gets a role. Set a default role for sign-ups. See 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.
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. Ask your AI assistant to update the authentication provider of type ARCHIE_AUTH with this configuration, using the manage_authentication tool with action: update.
  • 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.
.env
Create the client once and give it to ArchieProvider.
archie.ts
main.tsx
Install both packages with npm install @archie/js-sdk @archie/react-sdk.
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.
flow.tsx
Wrap your app with FlowProvider, inside ArchieProvider.

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. You can also pass a roleId in the sign-up request, but it must be one of the roles in allowed.
useAuth methods never throw. Check error instead.

2. Sign in the first time

A user who has no factor yet gets one of two results.
signIn does not report a missing second factor as an error. It returns an mfa object and keeps error as null.

3. Start the set up

Ask the backend for a new authenticator secret. The response has three values. Let the user choose how to add the account: scan the QR code, or type the setup key. Show both options.
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.

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.
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.
Then show the codes and wait for an explicit confirmation.

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

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

7. Read the policy and the factors

Use these queries to build a security settings page. Both need a session.
Use recoveryCodesLowWarning to prompt the user to regenerate the codes.

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.

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.
The SDK refreshes the session automatically. Sign out with useAuth().signOut().

Errors by code

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

Common implementation mistakes

These mistakes happen in real integrations. Check your code against them.
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.
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.
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.
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.
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.
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.
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.
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), or assign a role from the Users tab with Edit roles.

Next steps

Multi-factor authentication

Modes, grace period, and account recovery.

React SDK

Hooks and components for your React app.

JavaScript SDK

The core client for the browser and Node.js.

Archie Auth getting started

Enable Archie Auth and test the basic flow.