Skip to content

Custom sign-in flow

The prebuilt <SignIn /> runs this flow for you. To build your own form, drive the same sign-in attempt step by step: with the useSignIn hook from @zautha/react, or with zautha.signIn from @zautha/js. Both are the same SignInResource: every method returns { error } and never throws, and the resource keeps the attempt’s status, errors and fetchStatus, and its snapshot holds the rest of the state (supportedFirstFactors, firstFactorVerification, …), for you to render.

  1. Start the attempt with the user’s identifier (their email address or username) and a first factor.
  2. Read status: it says what the attempt waits for.
  3. When it is complete, call finalize(). That makes the new session the active one; until then the user is not signed in.
status The attempt waits for
needs_first_factor a first factor: snapshot.supportedFirstFactors lists them (password, email_code, email_link, passkey, …)
needs_second_factor a second factor of a user with two-step verification: supportedSecondFactors
needs_new_password resetPassword.submitPassword, after a correct reset code
complete finalize()
abandoned nothing: the attempt expired, start a new one
link_opened_elsewhere the code from the email, typed where the sign-in began (see email links)
import { useSignIn } from "@zautha/react";
import { useState, type FormEvent } from "react";
export function PasswordSignIn() {
const { isLoaded, signIn, errors, fetchStatus } = useSignIn();
const [identifier, setIdentifier] = useState("");
const [password, setPassword] = useState("");
if (!isLoaded || signIn === null) return null;
async function submit(event: FormEvent) {
event.preventDefault();
const { error } = await signIn!.password({ identifier, password });
if (error !== null) return; // the problem is in `errors`
if (signIn!.status === "complete") await signIn!.finalize();
// "needs_second_factor": render the second factor step (below)
}
return (
<form onSubmit={submit}>
<input value={identifier} onChange={(e) => setIdentifier(e.target.value)} autoComplete="username" />
{errors.fields.identifier && <p>{errors.fields.identifier.message}</p>}
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
/>
{errors.fields.password && <p>{errors.fields.password.message}</p>}
{errors.global.map((e) => (
<p key={e.message}>{e.message}</p>
))}
<button disabled={fetchStatus === "fetching"}>Sign in</button>
</form>
);
}

Without React, the same calls on zautha.signIn; subscribe to see the snapshot change:

import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
await zautha.load();
const { signIn } = zautha;
const { error } = await signIn.password({ identifier: "ada@example.com", password: "…" });
if (error === null && signIn.status === "complete") {
await signIn.finalize();
}
signIn.subscribe((snapshot) => console.log(snapshot.status, snapshot.fetchStatus, snapshot.errors));

password starts a new attempt unless one for the same identifier already waits for its first factor. After a few failed attempts a production instance asks for its bot check; the SDK gets the token and repeats the call (see Bot protection).

import { Zautha } from "@zautha/js";
const { signIn } = new Zautha("pk_test_…");
// Starts the attempt if needed and emails a code:
await signIn.emailCode.sendCode({ identifier: "ada@example.com" });
// The user types it:
const { error } = await signIn.emailCode.verifyCode({ code: "123456" });
if (error === null && signIn.status === "complete") await signIn.finalize();

The attempt’s firstFactorVerification says how many tries are left (attemptsRemaining) and when the code expires (expiresAt). A wrong code is the field error form_code_incorrect on code.

import { Zautha } from "@zautha/js";
const { signIn } = new Zautha("pk_test_…");
await signIn.resetPassword.sendCode({ identifier: "ada@example.com" });
await signIn.resetPassword.verifyCode({ code: "123456" }); // status becomes "needs_new_password"
await signIn.resetPassword.submitPassword({ password: "a new, long passphrase" });
if (signIn.status === "complete") await signIn.finalize();

Zautha signs the user out of every other session when the new password is set. A password that is too short or known from a breach is the field error form_password_length or form_password_pwned on password.

A user with two-step verification is asked for a second factor after the first: status is needs_second_factor and supportedSecondFactors lists what they have (totp, backup_code while one is left, passkey).

import { useSignIn } from "@zautha/react";
import { useState } from "react";
export function SecondFactor() {
const { signIn, errors } = useSignIn();
const [code, setCode] = useState("");
if (signIn === null || signIn.status !== "needs_second_factor") return null;
async function verify(kind: "totp" | "backupCode") {
const { error } = await signIn![kind]({ code });
if (error === null && signIn!.status === "complete") await signIn!.finalize();
}
return (
<div>
<input value={code} onChange={(e) => setCode(e.target.value)} autoComplete="one-time-code" />
{errors.fields.code && <p>{errors.fields.code.message}</p>}
<button onClick={() => verify("totp")}>Verify</button>
{signIn.supportedSecondFactors.includes("backup_code") && (
<button onClick={() => verify("backupCode")}>Use a backup code</button>
)}
{signIn.supportedSecondFactors.includes("passkey") && (
<button onClick={() => signIn.passkey()}>Use a passkey</button>
)}
</div>
);
}

signIn.totp({ code }), signIn.backupCode({ code }) and signIn.passkey() each answer the factor the attempt waits for. A used backup code is gone.

signIn.passkey() asks the browser for one of the user’s passkeys. It starts a sign-in without an identifier (the passkey names the user), or answers the first or second factor of the attempt you have. A passkey counts as both factors, so the sign-in completes without a second step.

import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
await zautha.load();
if (zautha.isPasskeySupported()) {
const { error } = await zautha.signIn.passkey();
if (error === null && zautha.signIn.status === "complete") await zautha.signIn.finalize();
}

The user closing the browser’s dialog is not an error to show; see Passkeys for autofill, the RP ID rules and the passkey_cancelled error.

A failed call returns its error and also fills errors, so a form can show each problem next to its field:

  • errors.fields has one entry per field, keyed by the camelCase parameter name (identifier, password, code). Each is a ZauthaApiError with the field’s code and message: form_identifier_not_found, form_password_incorrect, form_code_incorrect, form_password_pwned, …
  • errors.global has the errors that belong to no field: a lockout (identifier_locked), a rate limit, a network problem (ZauthaNetworkError). It is an array of ZauthaError.

Branch on code, never on message; every code has a page in the error catalog. A sign-in never returns identifier_not_allowed: sign-up restrictions apply to new sign-ups and to email addresses added to an account, never to signing in, so a user whose address is now blocked can still sign in. That code appears in the sign-up flow.

fetchStatus is "fetching" while a call runs; disable the submit button with it. signIn.reset() forgets the attempt (for “use another account”).

signIn.authenticateWithRedirect({ strategy: "oauth_google", redirectUrl, redirectUrlComplete }) leaves for the provider; the page at redirectUrl calls zautha.handleRedirectCallback(). See Social sign-in. signIn.create({ strategy: "ticket", ticket }) signs in with an organization invitation’s ticket.