@zautha/js API
The reference of everything @zautha/js exports. @zautha/js explains how the pieces fit
(two-step verification, passkeys, social sign-in, organizations); this page lists the API.
new Zautha(publishableKey, options?)
Section titled “new Zautha(publishableKey, options?)”import { Zautha } from "@zautha/js";import { ui } from "@zautha/ui";
const zautha = new Zautha("pk_test_…", { ui, // the prebuilt components; needed for mount*/open* only signInUrl: "/sign-in", // where sign-in lives; defaults to the hosted login signUpUrl: "/sign-up",});await zautha.load();The key decodes to the instance’s Frontend API host; nothing else is needed to reach it. One instance per key.
| Option | Meaning |
|---|---|
ui |
the @zautha/ui module; required for mount* and open* |
appearance |
passed to @zautha/ui (theme, variables, element classes) |
localization |
passed to @zautha/ui (texts) |
signInUrl, signUpUrl |
absolute, or a path on your site; default: the instance’s hosted login |
navigate |
full-page navigation; override it to use your router’s |
fetch |
the fetch used for every Frontend API request (tests, previews, runtimes without a global) |
afterSignOutUrl |
where signOut() and redirectToAfterSignOut() go; default /, null stays on the page |
initialState |
what your server saw (userId, sessionId, organization, actor), until load() settles |
load() reads the environment and the client, completes an email link or a development handoff in the address, and
resolves when the state is ready (or degraded/failed). Calling it again returns the same promise. dispose()
removes the instance’s listeners, timers and frames; call it when the page or component that created it goes away.
import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
const unsubscribe = zautha.subscribe((state) => { console.log(state.status, state.user?.id, state.organization?.role);});
if (zautha.isLoaded && zautha.isSignedIn) { console.log(zautha.user?.primaryEmailAddress, zautha.session?.id);}unsubscribe();zautha.state:{ status, environment, client, session, user, organization, initialState }.statusisloading,ready,degraded(the API was unreachable, the last known state is kept) orfailed.zautha.status,isLoadedandisSignedIn. Apendingsession (tasks left, e.g.setup_mfa) is not signed in.zautha.sessionis theSessionResource: the session plusgetToken(),reload()andverify().zautha.useris theUserResourcewith the self-service methods (update,createEmailAddress,createPasskey, …).subscribe(listener)returns the function that stops listening. Every other tab follows a change.
Tokens, sessions and organizations
Section titled “Tokens, sessions and organizations”import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
const token = await zautha.getToken(); // string, or null when signed out or pendingconst fresh = await zautha.getToken({ skipCache: true });
await zautha.setActive({ organization: "org_…" }); // an id, a slug (while the instance has slugs on), or null for the personal accountawait zautha.signOut({ redirectUrl: "/" });getToken throws ZauthaOfflineError when no token can be obtained. setActive resolves once the token carries the
new organization. signOut ends the session here and in every tab, then goes to redirectUrl, else to the
afterSignOutUrl option, else to /; a null (for either) stays on the page. redirectToAfterSignOut() goes to the
afterSignOutUrl target (/ by default; null stays) without signing out.
signOut waits for the first load(), because that is what says whether a session exists. When that load could not
read the client (the status is failed or degraded and there is no client, or the instance was disposed first), it
rejects with a ZauthaNetworkError, changes nothing and does not navigate: whether a session is alive is unknown. Handle
that rejection when you call useAuth().signOut(); <SignOutButton> has no error surface and does nothing then.
user.delete() deletes the account and the session with it; it does not navigate, so a custom delete button decides
where to go (redirectToAfterSignOut()). <UserProfile> does navigate after a deletion, to the same
afterSignOutUrl target. A page that handles account.deleted from onEvent and redirects on its own needs
afterSignOutUrl set (to that page’s URL, or null to stay), or the profile’s own redirect to / overrides yours.
createOrganization({ name, slug? }) and getOrganization(id) give an OrganizationResource.
Redirects and URLs
Section titled “Redirects and URLs”buildSignInUrl({ redirectUrl? }) and buildSignUpUrl(...) return the address of your sign-in or sign-up page (or the
hosted one); redirectToSignIn(...) and redirectToSignUp(...) navigate to it, with redirectUrl as where to come
back to. handleRedirectCallback() finishes a social sign-in or an account connection on the page the provider
returned to; see Social sign-in.
import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
const result = await zautha.handleRedirectCallback();if (result.status === "failed") console.error(result.flow, result.error.message);Components
Section titled “Components”With ui in the options, the prebuilt components render into your elements:
import { Zautha } from "@zautha/js";import { ui } from "@zautha/ui";
const zautha = new Zautha("pk_test_…", { ui });await zautha.load();
const element = document.getElementById("sign-in")!;zautha.mountSignIn(element, { signUpUrl: "/sign-up" });zautha.updateMounted(element, { signUpUrl: "/register" });zautha.unmount(element);
zautha.openUserProfile(); // as a modalzautha.closeUserProfile();mountSignIn, mountSignUp, mountUserButton, mountUserProfile, mountOAuthConsent, mountCreateOrganization,
mountOrganizationProfile and mountOrganizationSwitcher render a component; mount(name, element, props) takes the
component’s name. unmount(element) removes one and updateMounted(element, props) changes its props. The modals have
openSignIn, openSignUp, openUserProfile, openCreateOrganization and openOrganizationProfile, each with a
close… twin, and open(name, props). openReverification({ level }) opens the identity check and resolves when the
session has verified again (it rejects with ReverificationCancelledError when the user closes it).
isPasskeySupported() and isPasskeyAutofillSupported() say whether this page can use passkeys.
The attempt resources
Section titled “The attempt resources”zautha.signIn and zautha.signUp are SignInResource and SignUpResource; zautha.session.verify() is a
SessionVerificationResource. Each holds one attempt: a reactive snapshot (status, errors, fetchStatus, …),
subscribe(listener), methods that return { error } and never throw, finalize() and reset().
- Custom sign-in flow:
SignInResource. - Custom sign-up flow:
SignUpResource. - Custom email links:
emailLinkandcompleteEmailLinkon both. SessionVerificationResourceverifies the session again before a sensitive action:
import { Zautha } from "@zautha/js";
const zautha = new Zautha("pk_test_…");
const verification = zautha.session!.verify();await verification.create({ level: "first_factor" });if (verification.status === "needs_first_factor") { const { error } = await verification.password({ password: "…" }); if (error !== null) console.log(verification.errors.fields.password?.code);}Most apps never call it: withReverification (below) and the prebuilt components do.
Functions
Section titled “Functions”import { Zautha, checkAuthorization, parsePublishableKey, withReverification } from "@zautha/js";
const { frontendHost, environment } = parsePublishableKey("pk_test_…");// frontendHost: the Frontend API host; environment: "development" | "production"
const zautha = new Zautha("pk_test_…");
const mayRead = checkAuthorization(zautha.state.organization, { permission: "org:invoices:read" });
const updatePassword = withReverification(zautha, (password: string) => zautha.user!.updatePassword({ newPassword: password }),);parsePublishableKey(key)decodes apk_key; it throwsZauthaErrorfor a malformed one.checkAuthorization(organization, { permission | role })is the SDKs’hasrule: full keys, from the token alone,falsewithout an active organization.withReverification(zautha, fetcher)runsfetcher; when it needs a recent identity check (it throwsReverificationRequiredError, or resolves to a403 reverification_requiredresponse from your backend) it opens the check and runsfetcheronce more.useReverificationin@zautha/reactis the hook for it.
Errors are in SDK errors.