Skip to content

auth-react

@seek-services/auth-react connects a React app to one environment. It renders the login modal, keeps the session in a zustand store, calls your APIs with the user’s token, and has ready-made components for an account settings page. The same login UI is what SeekAuth serves as the hosted page. It is built on auth-js and needs React 18 or 19. Install it with npm install @seek-services/auth-react; see Installing.

import { AuthProvider, useAuthStore } from '@seek-services/auth-react'
export function App() {
return (
<AuthProvider issuer='https://your-app.auth.dev.seek.services' clientId='your-app-spa'>
<Header />
</AuthProvider>
)
}
function Header() {
const { user, status, login, logout, retry } = useAuthStore()
if (status === 'loading') return null
// not signed out: whether there is a session could not be found out
if (status === 'unavailable') return <button onClick={retry}>Can't reach the server. Try again</button>
return user ? (
<button onClick={logout}>Log out {user.email}</button>
) : (
<button onClick={login}>Log in</button>
)
}

login and logout take no arguments and ignore the click event, so they can be passed to onClick as they are.

<AuthProvider> adds the login UI’s stylesheet to the page itself, so there is nothing to import. Every rule is scoped to .seek-auth and every animation is prefixed seek-auth-, so nothing else on the page changes. An app that manages its own styles can import @seek-services/auth-react/styles.css instead.

The colours, corner radius, font, logo and wording come from the app’s theme (the Appearance page of the dashboard), not from props, and follow the device’s light or dark scheme.

Renders its children and the login modal. On mount it finishes a return from the hosted page (a URL with code or error and a matching state) and otherwise restores the stored session. Render it once, around everything that uses the SDK: the functions below throw not_configured without it.

Prop Type Meaning
issuer string The environment’s issuer URL, for example https://your-app.auth.dev.seek.services. Required.
clientId string The client’s client_id. Required.
backend string For a web client: the path your backend mounted auth-client’s routes on, such as /auth. The backend then holds the tokens and the browser only an HttpOnly cookie.
redirectUri string Where the hosted page and social logins return to. Default: the page the login started on. It must be one of the client’s redirect URIs.
postLogoutRedirectUri string Where the browser returns after logging out of a hosted-page session. Default: the page the logout started on. It must be one of the client’s post-logout redirect URIs.
scope string Default openid profile email offline_access.

There is no prop for the API the tokens are for. Name it per call with resource (see authFetch); without one, a token is for the client’s default API, or the account API when the client has none.

A zustand store: useAuthStore() (or a selector) in a component, useAuthStore.getState() anywhere else.

Member Type Meaning
user AuthUser | null The signed-in user, from the ID token: id, email, emailVerified, name, picture, acr (aal1 or aal2), amr, authTime.
status 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable' loading until the stored session has been checked. unavailable when that could not be found out: the user is not signed out, error says why, and retry() asks again. With a backend, only an answer counts: a user, none, or a 401. A failure that says nothing about the session (a backend restarting, 503 shutting_down; a refresh it cannot finish yet, 502; no network) is asked again a few times over about half a minute, after Retry-After and with backoff, then unavailable. Without one, a refresh is asked again only when the service said it spent nothing (temporarily_unavailable, 429): a refresh whose answer was lost may have rotated the token. A failure is then unavailable, and a refusal signs the user out.
error AuthError | null Why the last return from the hosted page, or the last restore, failed.
retry() Promise<void> After status: 'unavailable', asks again whether there is a session (loading meanwhile). Show “can’t reach the server” with a button for it, not an endless spinner. Does nothing in any other status.
login() Promise<AuthUser | null> Opens the login modal. Resolves with the user, or null when it was closed. A second call while it is open gets the same promise.
logout() Promise<void> Ends the session. See Sessions and sign-out.
stepUp(options?) Promise<AuthUser | null> Opens the modal for a stronger or more recent login of the current session: { acr?: string, maxAge?: number }. The server asks only for what is missing.
getAccessToken(options?) Promise<string> A valid access token, refreshed first when it ends within 30 seconds. { resource } gives one for that API. SPA clients only: a web client rejects with NotAvailableError.
createSessionTicket(targetClientId) Promise<string> A one-time ticket that signs this user in at another app of the same group. See Apps that share accounts.
loginWithRedirect(options?) Promise<void> Sends the browser to the hosted page instead of opening the modal.
sendEmailCode(email) Promise<EmailCodeChallenge> Starts an email-code login without the modal, for a login form of your own.
verifyEmailCode(code) Promise<AuthUser | null> Finishes it. Throws no_login_in_progress without a sendEmailCode first.
loginWithPasskey() Promise<AuthUser | null> A passkey login without the modal.
loginWithWallet(walletName?, options?) Promise<AuthUser | null> A wallet login without the modal. options.chain is 'solana' or 'evm'.
loginWithProvider(provider) Promise<void> Goes to a social or custom provider, always through the hosted page’s redirect.
deleteAccount(options?) Promise<void> Deletes the signed-in user’s account at once, with everything the service holds for it; there is no undo, and every session of it ends on every device. Goes through withStepUp: when the login is older than ten minutes or below the user’s highest level, the modal’s step-up opens and the deletion is asked once more. Then the user is signed out here (status: 'unauthenticated'). Rejects with the refusal and keeps the session otherwise: a step-up the user closed (StepUpRequiredError), or the service’s (sole_owner for a developer account that is the only owner of a workspace). An SPA asks the issuer with its own token; a web client asks its backend (DELETE {backend}/account/me) and then logs out there. With { stepUp: 'redirect' } (DeleteAccountOptions) the step-up goes through the hosted login page instead of the modal: the browser leaves, the promise does not settle, and the deletion is asked for again once the user is back. onStepUp is told while the modal is open. <DeleteAccount /> is the ready UI for it.

The functions for a login form of your own (sendEmailCode, verifyEmailCode, loginWithPasskey, loginWithWallet) hand the attempt to the modal when the server asks for more, such as a second factor or accepting the terms. A refusal throws an AuthError with error: 'insufficient_authorization', status: 403 and the rejection code in code. Wallet logins can also throw wallet_not_found, wallet_selection_required (several wallets and no name given) or wallet_error.

The login functions, authFetch, createSessionTicket and deleteAccount are also exported as plain functions: import { loginWithRedirect } from '@seek-services/auth-react'. The plain deleteAccount(options?) takes the same DeleteAccountOptions, or only an onStepUp as withStepUp does.

authFetch(input: RequestInfo | URL, init?: RequestInit & { resource?: string }): Promise<Response>

Calls your API as the signed-in user.

  • SPA client: adds Authorization: DPoP <access token> and a fresh DPoP proof for that request. On a 401 that says invalid_token it refreshes once and tries once more (not for a body that is a ReadableStream). resource picks the API the token is for.
  • Web client (backend set): a plain fetch with credentials: 'include', so your backend sees its session cookie; resource is ignored.
import { authFetch } from '@seek-services/auth-react'
const res = await authFetch('https://api.your-app.com/orders', { resource: 'orders-api' })
withStepUp<T>(action: () => Promise<T>, onStepUp?: (open: boolean) => void): Promise<T>

Runs action. When it fails with a StepUpRequiredError (the account API asked for a stronger or more recent login), opens stepUp with what the error asked for and runs action once more. If the error names nothing, as when a backend passed the refusal on without its WWW-Authenticate header, it asks for a fresh login (maxAge: 0). If the user closes the modal, the original error is thrown. onStepUp(true) and onStepUp(false) bracket the modal, for a spinner.

import { errorFromResponse } from '@seek-services/auth-js'
import { authFetch, withStepUp } from '@seek-services/auth-react'
// A change in the account API, which answers step_up_required when the login is not recent.
await withStepUp(async () => {
const res = await authFetch(`${issuer}/account/v1/password`, {
method: 'POST',
resource: 'account',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ new_password: password }),
})
if (!res.ok) throw errorFromResponse(res, await res.json().catch(() => null))
})

authFetch resolves with any response; the action has to throw for withStepUp to act. auth-js’s errorFromResponse makes a StepUpRequiredError of an answer whose body code is step_up_required. An API of yours that answers insufficient_user_authentication (as auth-client’s require_aal2 does) is handled with stepUp instead: see Step-up.

Four components cover an account settings page. Put them anywhere inside <AuthProvider>; the first three each have a hook with the same data for a UI of your own, and <DeleteAccount /> has deleteAccount() in the store. Every change they make asks for a recent login first, with withStepUp.

The signed-in user’s passkeys: list, add, rename, remove. Props: title (default Passkeys), className.

usePasskeys() returns status (loading, ready, error), passkeys, rpId, max (the most a user can have, 10), error, steppingUp, unavailable, and reload(), add(name?), rename(id, name), remove(id). unavailable says why passkeys cannot be added here, or is null:

unavailable Why
unsupported The browser has no WebAuthn.
not_configured The environment has no passkey domain.
wrong_domain This page is not on the passkey domain or under it.
limit The user already has the most passkeys allowed.

Adding a first passkey can return recovery codes (AddedPasskey.recovery_codes); the component shows them once.

An authenticator app (TOTP, with a QR code to scan) and recovery codes. Props: title (default Two-step login), className.

useTwoStep() returns status, totp, passkeys, recoveryCodesLeft, error, steppingUp, and reload(), start() (resolves { secret, otpauth_uri, enrollment_token }), confirm(setup, code) (resolves the recovery codes), remove(), newRecoveryCodes().

The social and custom providers linked to the account, linking another and unlinking. Props: title (default Linked accounts), className.

useIdentities() returns status, identities, available (the providers that can still be linked), error, steppingUp, returned, and reload(), link(provider), unlink(id). link leaves the page for the provider and comes back to the same address with #link_code=… or #link_error=…; the hook reads it, removes it from the address and finishes the link. returned is then { status: 'linked', identity } or { status: 'failed', error }. See linking a provider.

Deleting the account: a panel with the app’s own words on what that means there, and a button that asks the user to type the account’s email address before it deletes anything. Then the step-up when the login is not recent enough, the deletion, and the user is signed out here.

Prop Type Meaning
children ReactNode What deleting the account means in your app: what goes with it there, what you keep because the law says so, what to do first (download something, cancel a subscription). Shown on the panel, before anyone confirms.
onDeleted () => void Called once the account is gone and the user is signed out here. Send them to a page that says so.
confirmWord string What to type when the account has no email address (a wallet login). Default DELETE.
labels Partial<DeleteAccountLabels> Every text the panel and its dialog show, in your app’s language; the ones left out stay English (DELETE_ACCOUNT_LABELS). See below.
title string The panel’s heading, the same as labels.title (this one counts when both are given). Default Delete account.
stepUp 'modal' | 'redirect' How the recent login the deletion may need is asked for: the SDK’s login modal on the page (modal, the default), or the issuer’s hosted login page (redirect). See below.
className string Added to the panel’s root element.
import { DeleteAccount } from '@seek-services/auth-react'
import { useNavigate } from 'react-router-dom'
export function DangerZone() {
const navigate = useNavigate()
return (
<DeleteAccount onDeleted={() => navigate('/goodbye')}>
<p>
Your stores go offline at once and everything in them is erased within 30 days. Download
your orders first: we keep payment records only as long as the law requires.
</p>
</DeleteAccount>
)
}

The confirmation takes the address however it is written (spaces around it, other capitals). The panel shows nothing to someone signed out. A refusal of the service is shown in the dialog, which stays open. See deleting the account.

labels covers every string the component renders. The ones that name something are functions, so that each language can put the words in its own order:

Label Type English
title string Delete account
account (appName) => string your {app} account (your account when the environment has no name)
description (account) => string Deletes {account} and what is kept with it: … It happens at once and cannot be undone.
open string Delete account (the button)
dialogTitle string Delete your account?
dialogText (account) => string This deletes {account} at once and logs you out everywhere.
irreversible string Nothing brings it back.
confirmAgain string Said instead of dialogText when the user is back from a redirect step-up.
confirmLabel (expected) => string Type {email or confirm word} to confirm
cancel, confirm string Cancel, Delete my account
stepUpRequired string The user closed the login the deletion needed.
refusal (error: AuthError) => string The service refused: switch on error.code ?? error.error (sole_owner, rate_limited, network_error, …). The service’s English message by default.
failed string Anything else that went wrong.

labels is a Partial: a key you leave out falls back to English, which suits a page that changes two words. A full translation types its object as DeleteAccountLabels, and the compiler then asks for every key:

import { DeleteAccount, type DeleteAccountLabels } from '@seek-services/auth-react'
const de: DeleteAccountLabels = {
title: 'Konto löschen',
account: (app) => (app ? `dein ${app}-Konto` : 'dein Konto'),
description: (account) => `Löscht ${account} sofort, mit Profil, Anmeldewegen und Sitzungen.`,
// … every other key, or this does not compile
}
<DeleteAccount labels={de} />

The step-up: with stepUp='modal' the SDK’s login modal opens over the page and asks for what the service wants (a new login within ten minutes, the second factor when the user has one), and the deletion is asked once more when it closes. Its screens are the login’s own. With stepUp='redirect' the browser goes to the issuer’s hosted login page instead (loginWithRedirect with the max_age and acr_values the service named) and comes back to the app’s redirect URI, the account untouched; when that page shows <DeleteAccount /> again, its confirmation opens by itself (confirmAgain) and the user confirms once more. redirect suits an app that does not use the modal otherwise, such as a web client whose logins all go through the redirect door; the client needs that redirect URI registered.

Export What it is
<ProviderMark id /> The mark a provider’s button shows (google, apple, github, discord, x, microsoft), or a generic one for a custom provider. Sized 1em outside the login UI.
<LoginFlow client config onComplete … /> The login UI on its own, for a page that drives a ChallengeClient (from auth-js’s AuthClient.beginLogin()) itself. Other props: onProvider, onRedirectRequired, onRestart, titleId, wallets.
<ThemeRoot theme? /> The .seek-auth element with a theme’s CSS variables, for UI that should match the login.
listWallets(chain?) The browser wallets found on the page: Solana wallets from the Wallet Standard registry, EVM wallets from EIP-6963 (or window.ethereum when none announces itself).
AuthError, NotAvailableError, StepUpRequiredError Re-exported from auth-js. See errors.
passkeysSupported, passkeyAllowedHere, conditionalMediationAvailable Re-exported from auth-js.

The modal and the hosted page show exactly the login methods the environment has enabled, in the app’s theme. Two of them also depend on the page:

  • Passkeys are offered (“Sign in with a passkey”, passkeys in the autofill of the email field, and a passkey as a second step) only when the browser has WebAuthn and the page’s host is the passkey domain or under it. A one-label domain such as localhost covers that host alone.
  • Wallets are found in the browser as listWallets finds them. With Solana and EVM both enabled they share one chooser, each entry labelled with its family.

A captcha (Cloudflare Turnstile) is shown when the server asks for one; see Bot protection. Social and custom providers always leave through the hosted page’s redirect, even from the modal.