Building Your ApplicationFrontend

Frontend

On this page

Introduction

Keyring is headless. It renders pages with props and answers JSON requests, and your app owns every page. @keyringjs/keyring is a browser package that handles WebAuthn, enrolling sign-in methods, and the Vue and React bindings, for Inertia or for a frontend Laravel doesn't serve.

Terminal
npm install @keyringjs/keyring

The package works with the PHP package. It should work with the Rust crate too, since both answer the same JSON and the contract suite simulates its requests.

The package is plain ES modules. Pick the entry point that matches your setup:

Import Contains
@keyringjs/keyring The helpers that need no framework: WebAuthn, enrolling and sessions, single sign-on, json(), configureRequests(), configureRoutes(), routes and types.
@keyringjs/keyring/inertia The challenge helpers, for Inertia with any framework.
@keyringjs/keyring/vue Everything above, plus useChallenge() and usePasskeyLogin() for Vue, on Inertia.
@keyringjs/keyring/react The same for React, on Inertia.
@keyringjs/keyring/headless The headless helpers, posting with json(). No framework code.
@keyringjs/keyring/vue-headless The headless helpers, plus useForm(), useChallenge() and usePasskeyLogin() for Vue, without Inertia.
@keyringjs/keyring/react-headless The same for React, without Inertia.

The vue-headless and react-headless entry points re-export the main entry point, and inertia, vue and react need Inertia. A Blade app without a bundler can copy the package's dist folder into public/ and import the main entry point from a <script type="module"> tag.

Without Inertia, Keyring renders Blade views named auth.login, auth.challenge and so on. You may write those yourself, or point any page elsewhere with Keyring::page.

Building the Pages

Keyring renders components named auth/login, auth/challenge and so on. The Pages page lists each one and its props. Most are plain forms that post to Keyring's routes. Two need the helpers:

  • The challenge page, and confirm for step-up, shows whichever factor comes next. useChallenge does the work.
  • The login page can offer passkeys and identity providers from its providers prop.

Settings pages for sign-in methods, sessions, devices and the email address are yours to build too, with the helpers below. The example application has every page, in React.

Five pages are where emailed links land: reset-password, email-verification, email-change, device-report, and sign-in-link once email codes send a link. The link carries a token or a signature in its URL, and opening the page does nothing. Each page's form posts that secret in the body, to a URL without it:

Page Post To With
reset-password /reset-password token, email, password, password_confirmation
email-change its url prop token
email-verification its url prop expires, signature
device-report its url prop expires, signature
sign-in-link its url prop, in the browser that started the sign in code

The last four pages each have one button. In React, Inertia's <Form> component works:

TSX
import { Form } from '@inertiajs/react' export default function DeviceReport({ device, url, expires, signature }: { device: string, url: string, expires: string, signature: string }) {  return (    <Form action={url} method="post" transform={data => ({ ...data, expires, signature })}>      <p>This signs out {device}.</p>      <button type="submit">Sign that device out</button>    </Form>  )}

The email-verification page works the same way. The email-change page posts { token } and reads action (confirm or revert) to choose its wording. Don't put the token or signature back in the URL you post to. Keyring reads them from the body only.

The sign-in-link page has a button only in the browser that started the sign in. Anywhere else it asks for the code from the email to be typed where the sign in started, and once the link has ended it says so:

Vue
<script setup lang="ts">import { useForm } from '@inertiajs/vue3' const { code, sameBrowser, url, expiresAt } = defineProps<{ code: string | null, sameBrowser: boolean, url: string | null, expiresAt: string | null }>()const form = useForm({ code })</script> <template>  <!-- A failed post usually ends the link, so show its error in every branch. -->  <p v-if="form.errors.code">{{ form.errors.code }}</p>   <form v-if="sameBrowser" @submit.prevent="form.post(url!)">    <button :disabled="form.processing">Sign in</button>  </form>   <template v-else-if="expiresAt">    <p>This button only works in the browser where you started signing in. Type the code from the email in that browser instead.</p>    <p>If you didn't start signing in, don't type it anywhere, and change your password.</p>  </template>   <p v-else>This link has expired or has been used. Go back to where you started signing in, and send a new code from there.</p></template>

These pages are sent with Referrer-Policy: no-referrer, since their address holds the secret. After a successful form, Keyring has Inertia load the next page in full, so the rest of your app sends a referrer again.

The Challenge Page

The challenge page, and confirm, receives the challenge props. useChallenge turns them into what the page needs: the component for the current factor, a form, "try another way" and submitting.

Pass it a map of factor keys to components, for example in resources/js/keyring/factors.ts:

TypeScript
import { defineAsyncComponent } from 'vue' export default {  'password': defineAsyncComponent(() => import('./factors/Password.vue')),  'totp': defineAsyncComponent(() => import('./factors/Code.vue')),  'email-code': defineAsyncComponent(() => import('./factors/Code.vue')),  'recovery': defineAsyncComponent(() => import('./factors/Code.vue')),  'passkey': defineAsyncComponent(() => import('./factors/SecurityKey.vue')),  'security-key': defineAsyncComponent(() => import('./factors/SecurityKey.vue')),}

When you add a factor on the server, add one line to this map. In React, use lazy and a <Suspense> boundary instead.

Vue

Vue
<script setup lang="ts">import { useChallenge, type ChallengeProps } from '@keyringjs/keyring/vue'import factors from '../../keyring/factors' const props = defineProps<ChallengeProps>()const challenge = useChallenge(props, factors)</script> <template>  <component :is="challenge.component" :key="`${props.factor}:${props.authenticator.id}`" :challenge="challenge" />   <label v-if="props.canTrustDevice">    <input v-model="challenge.form.trust" type="checkbox"> Don't ask again on this device  </label>   <button v-for="option in props.alternatives" :key="`${option.factor}:${option.id}`" @click="challenge.switchTo(option)">    {{ option.name }}  </button></template>

useChallenge(props, factors) returns a reactive object, typed Challenge:

Member Does
form An Inertia form with code, password and trust.
props The page props you passed in.
component The component for props.factor, or undefined when the map has none.
submit(data?) Posts the form, plus data and the authenticator's ID, to the verify route. Clears code and password afterwards.
switchTo(option) Visits the challenge page for one of props.alternatives.
send() Asks the server to send a code, for factors that send one.
verifyKey() Runs the WebAuthn prompt with props.challenge.options and submits the result. Closing the prompt does nothing. Other browser errors go to form.errors.credential.

Factor components receive challenge and read the page from challenge.props. If a factor has no component in the map, component is undefined. A good fallback is your security key component when the challenge has WebAuthn options, and your code component otherwise.

React

TSX
import { useChallenge, type ChallengeProps } from '@keyringjs/keyring/react'import { Suspense } from 'react'import factors from '../../keyring/factors' export default function ChallengePage(props: ChallengeProps) {  const challenge = useChallenge(props, factors)  const { Component, form } = challenge   return (    <>      <Suspense fallback={null}>        {Component && <Component key={`${props.factor}:${props.authenticator.id}`} challenge={challenge} />}      </Suspense>       {props.canTrustDevice && (        <label>          <input type="checkbox" checked={form.data.trust} onChange={e => form.setData('trust', e.target.checked)} />          Don't ask again on this device        </label>      )}       {props.alternatives.map(option => (        <button key={`${option.factor}:${option.id}`} onClick={() => challenge.switchTo(option)}>{option.name}</button>      ))}    </>  )}

The React hook returns the same values as Vue's, except that the component is called Component, with a capital letter.

Factor Components

A factor component shows the right input and calls the challenge's methods. Factors that send codes include sent in their challenge props, so a component can show a "send code" button first:

Vue
<script setup lang="ts">import type { Challenge } from '@keyringjs/keyring/vue' const { challenge } = defineProps<{ challenge: Challenge }>()</script> <template>  <button v-if="'sent' in challenge.props.challenge && !challenge.props.challenge.sent" @click="challenge.send()">Send code</button>   <form v-else @submit.prevent="challenge.submit()">    <input v-model="challenge.form.code" autocomplete="one-time-code" inputmode="numeric">    <p v-if="challenge.form.errors.code">{{ challenge.form.errors.code }}</p>    <button :disabled="challenge.form.processing">Verify</button>  </form></template>

autocomplete="one-time-code" lets the browser offer a code it has seen arrive, such as one from an email or a text message, and inputmode="numeric" brings up a number pad on phones. Whether a code is offered is up to the browser and the mail app, so the field must work without it. A recovery code has letters, so give the recovery factor a field without inputmode.

A security key component usually calls challenge.verifyKey() as soon as it mounts, and shows a "try again" button in case the user dismisses the prompt. Under React's StrictMode, guard the call with a ref so the prompt opens only once.

Signing In With a Passkey

usePasskeyLogin runs a usernameless passkey sign in. It fetches the options, asks the browser for a passkey, and posts the result:

Vue
<script setup lang="ts">import { usePasskeyLogin } from '@keyringjs/keyring/vue'import { useForm } from '@inertiajs/vue3' const form = useForm({ email: '', password: '', remember: false })const { supported, processing, error, signIn } = usePasskeyLogin({ autofill: true, remember: () => form.remember })</script> <template>  <input v-model="form.email" type="email" autocomplete="username webauthn">   <button v-if="supported" :disabled="processing" @click="signIn()">Sign in with a passkey</button>  <p v-if="error">{{ error }}</p></template>
Option Does
autofill Also offers passkeys in the email field's autofill, where the browser supports it. The field needs autocomplete="username webauthn".
factor The factor key. Defaults to passkey.
remember A function returning whether "remember me" is ticked, read when the passkey is used.

It returns supported (whether the browser has WebAuthn), processing, error and signIn. In Vue, the first three are refs. Starting a sign in cancels one already in progress. Closing the prompt isn't an error, and processing is also true while a passkey picked from autofill is checked.

If your starter kit's passkey button uses @laravel/passkeys, you can keep it. It signs in through the same two routes once you give it their paths. Adding a passkey and the challenge page still need the helpers here.

Signing In With an Identity Provider

When the SingleSignOn factor is registered, the login page's providers prop lists the providers to offer. Each has a name, a label and the url that starts a sign in. Link to the url, adding ?remember=1 for "remember me". The LoginProps and IdentityProvider types describe them:

TSX
import type { LoginProps } from '@keyringjs/keyring' export default function Login({ providers, status }: LoginProps) {  return (    <>      {status && <p>{status}</p>}      {providers.map(provider => (        <a key={provider.name} href={provider.url}>Sign in with {provider.label}</a>      ))}    </>  )}

The browser leaves your site for the provider, so use a plain link. When the sign in fails, the user comes back to the login page with the error on the username field, in errors.

To link an account at a provider from a settings page, call linkProvider(). It needs the password while the account has a password and no established second factor. Failures, such as the 423 of step-up, throw a KeyringRequestError before the browser leaves. When the provider sends the user back, Keyring returns them to the page they started from, with the authenticator-added status.

Function Does
linkProvider(provider, { password? }) POST /user/authenticators/sso, then sends the browser to the provider.
signInWithProvider(provider, { remember? }) Gets the provider's URL from GET /auth/{provider}/redirect as JSON, then sends the browser there. Use it from a frontend on another origin.
confirmWithProvider(authenticator) Gets the URL from GET /confirm/sso/redirect as JSON, then sends the browser there, to confirm a step-up.

On the confirm page, a link at an identity provider is offered like any other method, with a challenge of type SsoChallenge (provider, label, url). On a confirm page Laravel renders, link to that url. From another origin, call confirmWithProvider(authenticator.id). For a provider whose freshness is never, the default for Google and GitHub, the link only counts toward a level such as AAL2, never for keyring.fresh. So the confirm page still needs an sso factor component for those providers.

The routes.ssoRedirect(provider), routes.ssoCallback(provider) and routes.ssoConfirm(authenticator?) helpers give the paths. See Single Sign-On for setting up providers and the callback page.

Challenge Helpers Without Vue or React

The Vue and React bindings are thin layers over these helpers. They're exported from @keyringjs/keyring/inertia, and the Vue and React entry points re-export them. Use them to build the challenge page or a passkey sign in with another framework. They post with Inertia's router (@inertiajs/core).

Function Does
challengeFields() The fields a challenge form starts with: code, password and trust.
switchTo(props, option) Visits the challenge page for one of props.alternatives.
sendCode(props) Asks the server to send a code for the current authenticator.
keyCredential(props, signal?) Runs the browser prompt with props.challenge.options, resolving to the credential to post as credential.
keyPrompt() Makes a prompt function for a challenge page. await prompt(props) resolves to the credential, or null when the user closed the prompt or a newer call replaced it.
passkeyCredential(factor, { autofill?, signal? }) Fetches the usernameless options and runs the prompt, or autofill.
signInWith(factor, credential, remember, { onError, onFinish }) Posts a credential from passkeyCredential() to sign in. onError gets the first error message.
passkeyLogin(options, onChange) The state behind usePasskeyLogin(): call start() once mounted, signIn() for the button and stop() when unmounting.
isAbort(error) Whether the user closed the prompt, the prompt timed out, or a newer request replaced it.
errorMessage(error) A readable message for any thrown value.

Note

Browsers report a closed prompt and a timeout as NotAllowedError. They also throw it when WebAuthn isn't allowed at all, such as in a cross-origin iframe without the publickey-credentials-get permission. If a prompt never appears, check that first.

TypeScript
import { errorMessage, isAbort, passkeyCredential, signInWith } from '@keyringjs/keyring/inertia' try {  const credential = await passkeyCredential('passkey')  signInWith('passkey', credential, false, { onError: showError, onFinish: () => {} })} catch (error) {  if (!isAbort(error)) showError(errorMessage(error))}

Managing Authenticators

The enrollment helpers call the authenticator routes with JSON requests:

TypeScript
import { beginEnrollment, confirmEnrollment, enroll, linkProvider, makeDefault, removeAuthenticator, renameAuthenticator } from '@keyringjs/keyring' // One step for factors that need no input in between. An account with no// established second factor sends its password with the first one.const { authenticator, recoveryCodes } = await enroll('passkey', { name: 'Laptop', password })const { enrollment } = await enroll('recovery')   // enrollment.codes holds the new codes // An identity provider: the browser goes there, and comes back linked.await linkProvider('google', { password }) // Two steps for authenticator apps and email codes.const started = await beginEnrollment('totp', { name: 'Work phone', password })showQrCode(started.enrollment.qr)const added = await confirmEnrollment('totp', started.enrollment, { code }) await renameAuthenticator(added.authenticator.id, 'Personal phone')await makeDefault(added.authenticator.id)await removeAuthenticator(added.authenticator.id)
Function Does
beginEnrollment(factor, data?) POST /user/authenticators/{factor}. Resolves to { factor, enrollment }. Send password when the account has no established second factor, or the request fails with an error on password. See The Password for a First Second Factor. A proof goes here too.
confirmEnrollment(factor, enrollment, data?) POST /user/authenticators/{factor}/confirm. Runs the browser ceremony first for a WebAuthn factor (see isWebAuthn()). If the server refuses the response, the enrollment is spent, so start again. Resolves to { authenticator, recoveryCodes?, continue? }.
enroll(factor, data?) Both steps, one after the other. data goes to both requests, except password and proof, which go only to the first.
renameAuthenticator(id, name, { proof }?) PATCH with name. Resolves to { authenticator }.
makeDefault(id) PATCH with default: true. Recovery codes and identity provider links can't be the default, and throw a KeyringRequestError with a 422 on default.
removeAuthenticator(id, password?, { signOutOthers, proof }?) DELETE. Removing the last second factor also needs the password. signOutOthers: true also ends the user's other sessions.
proveWithKey(factor, { action, target, name? }) Gets a challenge for one change from POST /user/authenticators/{factor}/proof-options, runs the ceremony, and resolves to a FreezeProof.
frozenChanges(error) The FrozenChanges a request was refused for, or null when it wasn't refused as frozen.
isWebAuthn(enrollment) Whether the server sent WebAuthn creation options for the enrollment.

When adding, pass sign_out_others: true in data to confirmEnrollment() or enroll() to end the user's other sessions.

If recoveryCodes comes back, show the codes and ask the user to save them. If continue comes back too, it's the page the user was going to when Keyring sent them to enroll. Offer it as a "Continue" link once the codes are saved. See Carrying On Afterwards.

Frozen Changes

Removing or renaming an established authenticator, or replacing established recovery codes, while the account's sign-in methods are frozen fails with a 422. Show error.errors.authenticator, which says how long is left. error.data.frozen is a FrozenChanges: its reason, an ISO 8601 until, and skip, the factors that could make the change now. frozenChanges(error) reads it for you.

When skip names a passkey or security key, offer "Use your passkey to do this now". proveWithKey() gets a challenge for that one change, runs the ceremony and returns the proof to send the request again with. See Making a Change With an Established Key:

TypeScript
import { frozenChanges, KeyringRequestError, proveWithKey, removeAuthenticator } from '@keyringjs/keyring' try {  await removeAuthenticator(id)} catch (error) {  const frozen = frozenChanges(error)   if (!(error instanceof KeyringRequestError) || frozen === null) {    throw error  }   message.value = `${error.errors.authenticator[0]} (${new Date(frozen.until).toLocaleString()})`  // Offer a button for this when frozen.skip has the user's key factor.  canUseKey.value = frozen.skip.includes('passkey')} // When they press it:const proof = await proveWithKey('passkey', { action: 'remove', target: id })await removeAuthenticator(id, undefined, { proof })

For a rename, prove { action: 'rename', target: id, name } and pass the proof to renameAuthenticator(id, name, { proof }) with the same name. For new recovery codes, prove { action: 'replace', target: 'recovery' } and pass the proof to beginEnrollment('recovery', { proof }) or enroll(). A confirm never takes a proof, so if it's refused as frozen, begin again with a proof. Where the server allows an authenticator app (skip_with_totp), skip lists totp. Send { factor: 'totp', code } as the proof, with authenticator set to the app's ID when the user has more than one.

Sessions

Three helpers call the session routes:

TypeScript
import { endOtherSessions, endSession, listSessions } from '@keyringjs/keyring' const sessions = await listSessions() await endSession(sessions[1].id)   // one session, by its handleawait endOtherSessions()           // every session but this one
Function Does
listSessions() GET /user/sessions. Resolves to the sessions, most recently active first, each a Session: id, name, ip, device, remembered, signedInAt, lastActiveAt, expiresAt, current, impersonated and impersonator ({ name }, or null).
endSession(id) DELETE /user/sessions/{id}. Ending the current one signs the user out, so send them to the login page.
endOtherSessions() DELETE /user/sessions.

The id is a handle that only these routes accept. It stays the same when the session moves to a new record. Once the session ends, or the app key is rotated without APP_PREVIOUS_KEYS, the handle stops matching, so list the sessions again before ending one from a list that's been open a while. An old handle gets a 404. Ending sessions needs a fresh verification, as the authenticator helpers do. See Handling Step-Up in JavaScript.

impersonate(id) and stopImpersonating() call the impersonation routes. The Impersonation type describes what Keyring::impersonation() shares for a banner.

Handling Step-Up in JavaScript

The authenticator routes need a fresh verification. When the user doesn't have one, a JSON request fails with a 423 status and a redirect to the confirm page. The helpers throw a KeyringRequestError with that status:

TypeScript
import { KeyringRequestError, enroll } from '@keyringjs/keyring'import { router } from '@inertiajs/vue3' async function addPasskey() {  try {    await enroll('passkey', { password })  } catch (error) {    if (error instanceof KeyringRequestError && error.status === 423) {      router.visit(error.data.redirect)      return    }     throw error  }}

After a JSON 423, Keyring remembers the page that made the call, from its Referer header, when that's a page on one of the app's own origins. Once the user confirms, they return there. You can also protect the page's own GET route with the keyring.fresh middleware. Then step-up happens when the page loads, and the JSON calls on it pass while the verification is fresh:

PHP
Route::get('/settings/security', SecuritySettingsController::class)    ->middleware(['auth', 'keyring.fresh:15m']);

Note

Use a window no longer than the one in changes_middleware, so the page doesn't outlive the routes it calls.

The same applies to your own routes protected by keyring:aal2 or keyring.fresh that you call with fetch or json. Without Inertia, destination(error) from the headless helpers reads the page and redirect of the 423.

JSON Requests

json(method, url, body?) is a small fetch wrapper that the helpers use. It sends Accept: application/json, X-Requested-With, and Laravel's XSRF-TOKEN cookie as X-XSRF-TOKEN. The token only goes to the page's own origin, or to the baseUrl when you set one. You may use it for Keyring's other JSON routes too:

TypeScript
import { json } from '@keyringjs/keyring' const { devices } = await json('GET', '/user/devices')const { pending } = await json('GET', '/user/email')await json('PUT', '/user/password', { current_password, password, password_confirmation })

On a non-2xx response, json() throws a KeyringRequestError with status, message, errors (Laravel's validation errors) and data (the whole body). A GET can't have a body, so json('GET', url, body) throws a TypeError before sending anything. Put a GET's fields in the query string.

WebAuthn Helpers

These helpers are useful for building your own flows:

Function Does
supportsWebAuthn() Whether the browser has WebAuthn.
supportsAutofill() Whether it can offer passkeys in autofill.
createCredential(options) Runs navigator.credentials.create() with Keyring's options, and returns the result as JSON for the server.
getCredential(options, { autofill?, signal? }) The same for navigator.credentials.get().
toBase64Url(buffer), fromBase64Url(value) Encoding helpers.

Changing Routes

The helpers use Keyring's default paths. If you changed the prefix option, tell the helpers once, at startup:

TypeScript
import { configureRoutes } from '@keyringjs/keyring' configureRoutes({ prefix: 'account' })

If you registered a route yourself, override it:

TypeScript
configureRoutes({  enroll: factor => `/account/authenticators/${encodeURIComponent(factor)}`,  confirmEnrollment: factor => `/account/authenticators/${encodeURIComponent(factor)}/confirm`,  authenticator: id => `/account/authenticators/${encodeURIComponent(id)}`,})

The keys are prefix, login, loginOptions, loginWith, challenge, verify, send, challengeBase, enroll, confirmEnrollment, authenticator, proofOptions, sessions, session, ssoRedirect, ssoCallback, ssoConfirm, impersonate and stopImpersonating. challengeBase(purpose) is the prefix the challenge routes share, so changing it moves all three:

TypeScript
configureRoutes({  challengeBase: purpose => purpose === 'login' ? '/account/login/challenge' : '/account/confirm',})

Keyring puts a factor's key or an ID into the URL as one encoded path segment. A . or .. throws a TypeError, since browsers resolve those away. An override is used exactly as written, without the prefix, so encode the values it receives too, as the enroll example does.

Update any paths your own pages link to directly, such as /login or /register.

Flash Messages and Alerts

Keyring's non-JSON responses flash a status slug to the session. JSON responses include it as status, with a readable message. Examples include code-sent, password-updated, device-revoked and email-change-requested. Extra data, such as new recovery codes, is flashed encrypted, so read it with Keyring::result rather than from the session. See Status Responses.

You can share them through your Inertia middleware, with the "was this you?" alerts. Keyring::statusMessage translates a slug from keyring::status.*, and returns null for anything else:

PHP
use Keyring\Facades\Keyring; public function share(Request $request): array{    return [        ...parent::share($request),        'status' => fn () => $request->session()->get('status'),        'statusMessage' => fn () => Keyring::statusMessage($request->session()->get('status')),        'keyringResult' => fn () => Keyring::result(),        'keyringAlerts' => fn () => $request->session()->get('keyring.alerts', []),        'impersonation' => fn () => Keyring::impersonation($request),    ];}

impersonation is null unless someone is impersonating the user. The login, forgot-password and verify-email pages already receive the translated message as their status prop.

A JSON request that completes a sign in gets the alerts in its answer, as alerts on the 200 authenticated. They're still flashed, so a page loaded after a JSON sign in shows them too. A frontend that reads alerts from the answer shouldn't also share the flash, or the banner shows twice.

After a user was sent to enroll, Keyring::result('continue') holds the page they were going to, once they've added a sign-in method that gets them in. It's only there on the request right after authenticator-added, so read it on the page that response sends the user back to. JSON clients get continue in that response's body. After a held password change, Inertia and Blade are redirected to that page, and JSON clients get it as redirect. A separate SPA that calls Keyring with JSON keeps its own route.

Frontends on Another Origin

By default, the package sends requests to the page's own origin, which is right when Laravel serves the frontend. When it doesn't, such as a Nuxt or Next app on app.example.com calling Laravel on api.example.com, tell the package where Laravel is, once, at startup:

TypeScript
import { configureRequests } from '@keyringjs/keyring' configureRequests({  baseUrl: 'https://api.example.com',  csrfCookie: '/sanctum/csrf-cookie',})

The Laravel side, with CORS, cookies and passkeys, is in Headless Frontends.

Option Does
baseUrl Where Laravel is, such as https://api.example.com. Every path json() sends goes there, Keyring's routes and yours alike. It may include a path, such as https://example.com/backend. It must be an absolute http or https URL with no credentials, query or fragment, or configureRequests() throws a TypeError. null goes back to the page's origin.
credentials The credentials of each fetch. Defaults to include for a request to a baseUrl on another origin, or when there's no page, as when rendering on the server. Otherwise same-origin.
csrfCookie A URL that sets the XSRF-TOKEN cookie, such as /sanctum/csrf-cookie. When the cookie is missing, json() fetches it before any request but a GET, once for requests made together. If the cookie arrives but the page can't read it, the request throws a KeyringRequestError with a 419, rather than posting without a token.
fetch A function to use instead of the global fetch. See Rendering on the Server.

Passing an option as undefined puts it back to its default. An option the package doesn't have, such as baseURL, throws a TypeError.

routes still holds paths, so routes.login is /login, and json() adds baseUrl when it sends one. configureRoutes() still sets the prefix, and the base URL goes in front of it. A path you write yourself, such as /api/user, goes to baseUrl exactly as written.

If the frontend reaches Laravel through a proxy on its own origin, such as app.example.com/backend, the requests are same-origin and need no CORS. Set baseUrl to the proxy's path, https://app.example.com/backend, rather than adding it to the prefix: a path the package is handed as it is, such as the url prop of the pages emailed links open, gets the baseUrl but not the prefix. See One Origin.

Cookies and CSRF

Sending the session cookie needs credentials: 'include' and CORS that allows credentials from your frontend's origin. Reading the XSRF-TOKEN cookie needs a SESSION_DOMAIN that both hosts share. Headless Frontends and Session Cookies cover both.

csrfCookie fetches the XSRF-TOKEN cookie before the first POST, and throws when the cookie arrives but the page can't read it. Without that option, fetch it yourself first:

TypeScript
await fetch('https://api.example.com/sanctum/csrf-cookie', { credentials: 'include' })

A 419 means the token was missing or didn't match: usually SESSION_DOMAIN is wrong, or the cookie was never fetched. The package doesn't depend on Sanctum: any route that sets the XSRF-TOKEN cookie works as csrfCookie.

Headless Vue and React

The vue-headless and react-headless entry points give a frontend without Inertia the same useChallenge() and usePasskeyLogin() hooks, and a useForm() in place of Inertia's. They post with json(), so configureRequests() applies to them. What Inertia did for the pages, your app does through one callback, navigate. It receives a Destination whenever an answer goes somewhere:

Member Is
page The name of one of Keyring's pages, such as challenge, confirm or login, or null.
redirect A URL on Laravel, or from your config, such as home.
status The answer's slug, such as authenticated.
httpStatus The HTTP status of a request that failed, such as 423 or 401, or null for one that worked.
answer The whole body.

Map each of Keyring's page names to a route of your frontend, and send the user back to where they were going once status is authenticated. The Nuxt example in Headless Frontends has a full navigate function, with the step-up and redirect handling you need.

Laravel's own 401 for a guest, {"message": "Unauthenticated."}, names no page, so the hooks read it as page: 'login', with httpStatus 401. A 401 whose body names a page, such as signed-out or sign-in-to-verify, goes there. Any other 401 names no page and stays put, with its message in error.

useForm(fields, { navigate? }) is shaped like Inertia's form and posts with json(), so it can't upload files. In Vue, the fields sit on the form for v-model, and a field can't be named after one of the form's own properties, such as errors, error, processing, data or submit. Doing so throws. In React, the fields are in form.data, set with form.setData(). With navigate, the form goes where the answer says, as Inertia's does: the 202 challenge, the 423 of step-up, or the page a status names.

A failure with no field errors and nowhere to go, such as a 419 or a network error, puts its message in error, until the next submit.

Each request resolves to an Answer: ok, data, errors, message, error (the KeyringRequestError, or null) and to (the Destination, or null). A request that got no answer, such as a network failure, resolves with ok: false, error: null and the reason in message. It doesn't reject.

Form member Does
errors, hasErrors Field errors, the first message for each field, and whether there are any.
error A failure with no field errors and nowhere to go. Vue sets it with form.error = message, React with form.setFormError().
processing True while a request is in flight.
setError(), clearErrors(...fields), reset(...fields) Set, clear or reset fields. clearErrors() with no fields also clears error.
get(), post(), put(), patch(), delete() Send the fields as the body, or as the query string for get().
Vue data(), React data and setData() Vue's data() returns the fields. React's data holds them, and setData(key, value) or setData({ ... }) changes them.
Submit option Does
transform Returns the body to send in place of the fields.
formError false leaves error alone, as useChallenge() does.
onSuccess(answer) Called when the request worked.
onError(errors, answer) Called when it didn't.
onFinish() Called last, after any navigating.

useKeyringNavigate is your own hook, ported from the Nuxt composable in Headless Frontends.

A login page in React:

TSX
import { routes, useForm, usePasskeyLogin } from '@keyringjs/keyring/react-headless'import { useKeyringNavigate } from '../keyring/navigate' export function LoginPage() {  const navigate = useKeyringNavigate()  const form = useForm({ email: '', password: '', remember: false }, { navigate })  const passkey = usePasskeyLogin({ autofill: true, remember: () => form.data.remember, navigate })   return (    <form onSubmit={(e) => { e.preventDefault(); form.post(routes.login) }}>      <input type="email" autoComplete="username webauthn" value={form.data.email} onChange={e => form.setData('email', e.target.value)} />      {form.errors.email && <p>{form.errors.email}</p>}      <input type="password" autoComplete="current-password" value={form.data.password} onChange={e => form.setData('password', e.target.value)} />      <button disabled={form.processing}>Sign in</button>      {form.error && <p>{form.error}</p>}       {passkey.supported && <button type="button" disabled={passkey.processing} onClick={() => passkey.signIn()}>Sign in with a passkey</button>}      {passkey.error && <p>{passkey.error}</p>}    </form>  )}

Identity providers are in the login page's providers prop, which loadPage(routes.login) returns in a headless app. Offer each with a button that calls signInWithProvider(provider.name, { remember }), rather than a link. The provider sends the user back to a callback page of your frontend, which passes the query on to Laravel. Signing In in Headless Frontends has the page.

useChallenge(purpose, factors, { navigate?, props? }) takes login or confirm in place of the Inertia hook's props, and loads them once mounted, in the browser only. The challenge belongs to the browser that signed in. Pass props if you already loaded them. It returns what the Inertia hook does, with a headless form, plus:

Member Is
props The page's props, null until they're loaded.
loading Whether props are on their way. The last ones stay in props meanwhile.
error A failure that's neither a field's error nor a page to go to, such as a 419, a network error, or a 401 with no navigate. Field errors are on form.errors.
reload() Loads the props again.

switchTo() and send() load the props again, so a code factor sees sent once the code is on its way. An answer that names this same page, such as a challenge for another factor, does too. Every other answer goes to navigate. A sign in that ran out names login with the reason in to.answer.errors, for your login page to show.

The challenge page is the Inertia one above, with useChallenge('login', factors, { navigate }). Read the page from challenge.props, which is null until they load, and show challenge.error and challenge.loading meanwhile. Building the Frontend With Nuxt has the page in full.

On the confirm page, an sso factor component calls confirmWithProvider(challenge.props.authenticator.id). The provider sends the user back through the same callback page, which gets authenticated. Factor components written for the Inertia hooks also work with these, as long as they only use challenge.props, the form's fields and errors, processing, submit(), send() and verifyKey(). Import the Challenge type from the headless entry point.

Headless Helpers

The headless hooks are built on these helpers, exported from @keyringjs/keyring/headless and re-exported by vue-headless and react-headless. Use them with another framework. Every request goes through json().

Function Does
destination(answer) The Destination an answer, or a KeyringRequestError such as a step-up 423, sends the browser to, or null when it names neither a page nor a redirect. Laravel's own 401 for a guest goes to page: 'login'.
request(method, url, body?) json(), resolving to an Answer for an error status too. A GET sends body in the query string, where json() throws. A request that got no answer, such as a network failure, still rejects.
fieldErrors(errors) Laravel's validation errors, the first message for each field.
submitForm(method, url, data, options, { setErrors, setProcessing, setFormError? }) What useForm() does on submit, with the form's state kept by your callbacks. options takes the same submit options as the form's methods.
loadPage(url) GET a page as JSON: { page, props }, or the status a page answers instead, such as email-verified.
loadChallenge(purpose, option?) The challenge or confirm page's props, for one { factor, id } or the default.
switchTo(props, option), sendCode(props) Load the props for another method, or send a code.
signInWith(factor, credential, remember, { onError, onFinish, navigate? }) Posts a credential from passkeyCredential() to sign in, and goes where the answer says.
passkeyLogin({ navigate?, ...options }, onChange) The state behind the headless usePasskeyLogin().
challengeFlow(purpose, { navigate?, props? }, form, onChange) The state behind the headless useChallenge(). form is a function returning your form's submit, setError, clearErrors and reset. onChange gets { props, loading, error }. Call start() once mounted and stop() when unmounting.

The shared challengeFields(), keyCredential(), keyPrompt(), errorMessage(), passkeyCredential() and isAbort() are there too.

For a passkey sign in with no framework, passkeyCredential() and json() do the work:

TypeScript
import { isAbort, json, passkeyCredential, routes } from '@keyringjs/keyring' try {  const credential = await passkeyCredential('passkey')  const answer = await json('POST', routes.loginWith('passkey'), { credential, remember: false })  // Sign in done, or a challenge to show next. Headless Frontends describes the answer.} catch (error) {  if (!isAbort(error)) showError(error)}

Go by an answer's page, then its redirect, as Where Each Answer Goes explains. A frontend on another origin never gets continue, so it keeps track of where the user was itself.

Rendering on the Server

On the server there's no document, so json() sends no XSRF token and doesn't fetch csrfCookie. The browser's cookies aren't there either, so a request made while rendering is a guest's unless you forward them. The simplest approach is to call the package's helpers in the browser only, such as in onMounted or a client-only plugin.

The fetch option suits anything the same for every request, such as an internal URL to reach Laravel, a fixed header, or logging:

TypeScript
configureRequests({  baseUrl: 'https://api.example.com',  fetch: (url, init) => fetch(url, { ...init, headers: { ...init.headers, 'Accept-Language': 'en' } }),})

Warning

configureRequests() sets one configuration for the whole JavaScript process. On a server that renders pages for many users at once, never pass a fetch that adds one user's cookies, since another user's render may use it. Forward cookies for a single request with your framework's request-scoped fetch, and call Keyring's routes with it directly. Nuxt's useRequestFetch() forwards the browser's cookies, but drops the Set-Cookie Laravel answers with, which can end a remembered session. Rendering on the Server in Headless Frontends covers the fix.

Don't pass Nuxt's $fetch or ofetch as fetch. They resolve to the parsed body rather than a Response.