Building Your ApplicationHeadless Frontends

Headless Frontends

On this page

Introduction

Most Keyring apps build their pages with Inertia or Blade, and Laravel serves them. This guide is for a frontend that Laravel doesn't serve, such as a Nuxt app on app.example.com calling Laravel on api.example.com. It's the same setup as Fortify with 'views' => false.

The browser signs in with Laravel's session cookie, as Sanctum's single-page app authentication does. Keyring's routes stay web routes, with a session, CSRF protection and Keyring's headers. Your frontend calls them with fetch, sends cookies and asks for JSON. Every route answers JSON, the pages included:

  • A form route answers with a status response, one of the other responses, or a validation error.
  • A page route answers with the page's name and props, so your frontend can render the page itself.
  • Whenever an answer sends the browser to one of Keyring's pages, it names that page, so your frontend can go to its own page of that name.

The examples use Nuxt, but any frontend that can send cookies works the same way. The configuration below is for the PHP package. The Rust crate answers the same JSON, configured in Rust rather than config/keyring.php, where pages.enabled = false is the same as 'pages' => false.

Choosing a Layout

The browser has to send Laravel's cookies with every request. Where the frontend lives decides how much setup that takes.

Layout Example
One origin Nuxt on example.com, passing everything under /backend to Laravel. Supported, with less setup: no CORS, and cookies, CSRF and passkeys work as they are. See One Origin.
Subdomains of one site app.example.com and api.example.com Supported. The rest of this guide sets it up.
Different sites example-app.com and example-api.net Not supported. The session cookie is SameSite=Lax, so the browser doesn't send it on a fetch() from another site, and browsers block third-party cookies anyway.

Sites are the same when they share a registrable domain, so app.example.com and api.example.com are one site. They're still different origins, so requests between them need CORS. The browser sends SameSite=Lax cookies with them.

Configuring Laravel

Pages and Redirects

Laravel renders none of Keyring's pages. Turn them off in config/keyring.php, and point the places Keyring sends users at your frontend:

PHP
'pages' => false, 'home' => 'https://app.example.com/dashboard', 'enrollment_url' => 'https://app.example.com/settings/security', 'password_change_url' => 'https://app.example.com/settings/password',

With pages off, a request for a page that isn't JSON gets a 404. JSON requests still get each page's props. home, enrollment_url and password_change_url reach the frontend as the redirect of the answers that use them, so full URLs on the frontend are what it can act on.

The enrollment_url and password_change_url only help the Laravel side. If keyring.enrolled is on your api routes or your own web routes, list the ones the frontend's enrollment page calls, such as the route behind GET /api/user, in enrollment_except, by route name. Keyring's own routes, signing out and email verification still answer.

During a password hold, only the password change, the confirm routes, signing out and email verification answer. Keyring's other routes get the 403 change-password. List the routes the frontend calls on every page in password_change_except, by route name, if they're held. See Requiring a Second Factor and Requiring a Password Change.

Keyring's paths go under a prefix, which keeps the CORS paths short and apart from your own routes:

PHP
'prefix' => 'auth',

Keyring's paths then start with /auth, such as /auth/login and /auth/login/challenge. This guide uses that prefix. If you use the browser package, tell it with configureRoutes({ prefix: 'auth' }).

Session Cookies

Set the session cookie's domain to the site, so every subdomain gets it:

.env
SESSION_DOMAIN=.example.comSESSION_SECURE_COOKIE=trueSESSION_SAME_SITE=lax

Sharing the cookie with the site is what lets the frontend's JavaScript read the XSRF-TOKEN cookie for CSRF, and lets the Nuxt server receive the session cookie when it renders a page. Laravel's XSRF-TOKEN cookie takes the same domain.

With session.domain set, Keyring's device and "remember me" cookies are shared with the subdomains too, and carry the __Secure- prefix rather than __Host-. See Keyring's Cookies. Every subdomain can then read and set them, so only share a domain whose subdomains you control. A domain that hosts other people's content, such as user subdomains, isn't safe to share.

Sanctum

Keyring's own routes don't need Sanctum. Sanctum is for your api routes, such as GET /api/user, so that auth:sanctum signs the browser in from its session cookie. Install it with php artisan install:api, turn on its stateful mode, and add Keyring's session middleware to the api group:

PHP
// bootstrap/app.php->withMiddleware(function (Middleware $middleware) {    $middleware->statefulApi();    $middleware->appendToGroup('api', 'keyring.session');})

statefulApi() starts the session for requests whose Referer, or Origin when there's no Referer, is one of the hosts in sanctum.stateful. Other requests are treated as token requests, with no session. Add the frontend's host:

.env
SANCTUM_STATEFUL_DOMAINS=app.example.com

Without keyring.session, a session that Keyring revoked or timed out keeps working on your api routes until Laravel's own session ends. The conformance suite fails for any auth:sanctum route without it.

Sanctum starts the session with Laravel's StartSession, which Keyring has replaced with its own. So an api request that overlaps a sign in, such as the frontend asking who's signed in as the sign in finishes, almost never undoes it.

CORS

The frontend's requests are cross-origin, so Laravel has to allow them with credentials. Publish config/cors.php with php artisan config:publish cors, then set:

PHP
'paths' => ['api/*', 'sanctum/csrf-cookie', 'auth/*'], 'allowed_origins' => ['https://app.example.com'], 'supports_credentials' => true,

Without a prefix, list Keyring's paths instead: login, login/*, logout, register, forgot-password, reset-password, reset-password/*, confirm, confirm/*, auth/*, user/*, email/*, email-changes/*, devices/*, impersonate and impersonate/*. The auth/* path holds the single sign-on routes, and impersonate is the route that stops an impersonation.

Warning

Never use 'allowed_origins' => ['*'] with supports_credentials. Laravel then allows whichever origin asks, so any other subdomain of your site could read Keyring's JSON with the user's cookies. The same goes for allowed_origins_patterns that match more than the frontend, such as every subdomain of example.com. List the frontend's exact origin.

CSRF

Keyring's routes keep Laravel's CSRF protection. A request from app.example.com to api.example.com is same-site, not same-origin, so Laravel's PreventRequestForgery middleware checks its token. The frontend sends the XSRF-TOKEN cookie's value as an X-XSRF-TOKEN header, as the browser package's json() and axios both do. Across origins, axios sends cookies and the header only when asked:

TypeScript
axios.defaults.withCredentials = trueaxios.defaults.withXSRFToken = true

The cookie is set on any response from a web route, but the usual first request is Sanctum's:

Terminal
GET /sanctum/csrf-cookie

Laravel can also accept every request from the same site without a token, with $middleware->preventRequestForgery(allowSameSite: true). That trusts every subdomain as much as the frontend, so keep the token unless you control them all.

Passkeys

A WebAuthn ceremony runs in the frontend's page, so the browser checks keys against the frontend's origin, not Laravel's. By default, Keyring uses the host of APP_URL as the relying party ID and its origin as the only one allowed, which here is api.example.com. Browsers refuse that ID on app.example.com, so set both in config/keyring.php:

PHP
'webauthn' => [    'relying_party' => [        'id' => 'app.example.com',    ],    'origins' => ['https://app.example.com'],],

The relying party ID has to be the frontend's host or a domain it belongs to. app.example.com keeps keys to the frontend. Use example.com only when users sign in with keys on several subdomains, and list each origin. Choose before anyone registers a key: changing the ID later makes existing keys stop working. See Relying Party and Origins.

Keyring builds emailed links from APP_URL, which here is Laravel's host. Start them at the frontend instead, in your KeyringServiceProvider's boot() method:

PHP
Keyring::linkRootUsing(fn () => config('app.frontend_url'));

Only the root changes. The paths stay Keyring's, so the frontend serves a page at each one. With the auth prefix:

Link Opens Page
Password reset /auth/reset-password/{token}?email=... reset-password
Email verification /auth/email/verify/{id}/{hash}?expires=...&signature=... email-verification
Email change, confirm or undo /auth/email-changes/{change}/confirm/{token}, /auth/email-changes/{change}/revert/{token} email-change
"This wasn't me" /auth/devices/{device}/report?expires=...&signature=... device-report
Sign in, from an email code's email with withLink() /auth/login/challenge/email-code/link?token=... sign-in-link

Some emails also link to /auth/login and /auth/forgot-password. The emails about a new sign-in method and new recovery codes link to your settings page when you set authenticators_url. A path there goes after the same root.

Signed links are signed over their path and query only, so the signatures hold under the frontend's root. The frontend sends the same path and query to Laravel, which checks the signature as if the link had opened there. A root with a path of its own works too: https://app.example.com/account starts the reset link at https://app.example.com/account/auth/reset-password/..., and the frontend leaves /account off the path it sends to Laravel.

Single Sign-On

With Keyring::linkRootUsing() set, the callback URL that Keyring gives identity providers starts at the frontend too, such as https://app.example.com/auth/auth/google/callback with the auth prefix. Register that URL with the provider, and serve a page at that path that passes its path and query on to Laravel as JSON. See Frontends Laravel Doesn't Serve.

The browser package's signInWithProvider(), linkProvider() and confirmWithProvider() use the JSON redirect routes for you, and Signing In shows the callback page.

Local Development

With Nuxt on http://localhost:3000 and Laravel on http://localhost:8000, both are the same site, and cookies don't keep ports apart:

.env
APP_URL=http://localhost:8000SESSION_DOMAIN=localhostSESSION_SECURE_COOKIE=false

Leaving SESSION_DOMAIN empty works too. SANCTUM_STATEFUL_DOMAINS already lists localhost:3000 unless you set it. Allow http://localhost:3000 in cors.allowed_origins. For passkeys, set webauthn.relying_party.id to localhost and webauthn.origins to ['http://localhost:3000']. Browsers allow WebAuthn on localhost without HTTPS.

Keep SESSION_SECURE_COOKIE off over plain HTTP. Chrome and Firefox accept a Secure cookie from http://localhost, but Safari refuses it, so a secure session cookie signs nobody in on Safari.

One Origin

The frontend can also serve Laravel from its own origin, under a path of its own, so the browser only ever talks to the site. Keyring's pages stay on the frontend, at /auth/..., and a server route of the frontend passes everything under /backend on to Laravel:

The Browser Asks For Served By
https://example.com/auth/login The frontend, the login page
https://example.com/backend/auth/login Laravel, /auth/login
https://example.com/backend/api/user Laravel, /api/user

Any path of the frontend's own works in place of /backend, as long as it isn't where Keyring's pages are. Don't pass /auth/* itself to Laravel. A proxy picks by path, not by Accept, so a full page load of /auth/login, or an emailed link to /auth/reset-password/{token}, would reach Laravel as a page visit, which is a 404 with pages off.

Set APP_URL to the site, https://example.com, not to the address the proxy reaches Laravel at. Keyring takes the relying party ID and allowed origin for passkeys, where emailed links start, and whether its own cookies are Secure and prefixed from APP_URL, never from the request.

The Proxy

A proxy that passes requests on looks simple, but each of these rules prevents a failure that's hard to trace back to it:

  • Pass Accept and X-Requested-With on. Keyring answers JSON when the request expects it: an Accept that names JSON first, or X-Requested-With: XMLHttpRequest with an Accept of */* or none. The browser package sends both. Without them, signing out, the challenge, step-up, a status, a validation error and the rest answer with a redirect, as they would to a page visit. h3's proxyRequest() leaves Accept out of what it passes on, so give it back yourself.
  • Don't follow redirects. h3's proxyRequest() and fetch() both follow them unless told not to. Pass a 3xx on to the browser as it is, with its Location and its Set-Cookie headers, and let the browser follow it. A proxy whose fetch() follows the redirect itself drops the cookies the redirect set. Signing in and signing out both give the session a new ID, and both answer with a redirect when the request doesn't expect JSON, so the browser is left holding the ID they replaced. For the first 10 seconds after that answer, nothing its requests put in the session is kept: the passkey options the login page asks for as it loads are lost, and the passkey sign in that follows fails with a 422, which looks like a fault in passkeys. After that the browser gets a fresh, empty session. Either way it's signed out. See Requests That Overlap a Sign In.
  • Pass cookies both ways. Send the browser's Cookie header on, and every Set-Cookie back as a header of its own. A Set-Cookie read with headers.get() comes back as one comma-joined string, which the browser takes for a single cookie, so read them with getSetCookie(). Laravel and Keyring can give the browser a new session cookie, a new XSRF-TOKEN and new device and "remember me" cookies on any request, and a dropped one leaves the browser holding one that's been replaced or used up (see A Cookie Used Twice).
  • Pass the CSRF headers on. Laravel lets a state-changing request through on Sec-Fetch-Site: same-origin, or on an X-XSRF-TOKEN header that matches the session. Pass both on as the browser sent them. Without either, every POST gets a 419.
  • Leave SESSION_DOMAIN empty. The cookies Laravel sets then belong to the site's host, which is the one the browser sees. A domain naming Laravel's own host makes the browser refuse them.
  • Don't cache. Keyring's answers carry Cache-Control: no-store, private. Pass that on, and don't let a cache in front of the frontend keep anything under /backend.

A Nitro server route does the passing on:

TypeScript
// server/routes/backend/[...path].tsimport { getRequestHeader, getRequestIP, proxyRequest } from 'h3' export default defineEventHandler((event) => {  const config = useRuntimeConfig()  const site = new URL(config.public.appUrl) // https://example.com  const path = event.path.replace(/^\/backend/, '')   return proxyRequest(event, config.laravelUrl + path, {    headers: {      // proxyRequest() leaves Accept out unless it's given here.      accept: getRequestHeader(event, 'accept') ?? '*/*',       // Replaced, never passed on: the browser can send any of these.      'x-forwarded-for': getRequestIP(event) ?? '',      'x-forwarded-host': site.host,      'x-forwarded-proto': site.protocol.slice(0, -1),      'x-forwarded-port': site.port || (site.protocol === 'https:' ? '443' : '80'),      'x-forwarded-prefix': '/backend',    },    // A redirect goes to the browser, with its cookies.    fetchOptions: { redirect: 'manual' },  })})

proxyRequest() passes the browser's other headers on, Cookie, X-Requested-With, X-XSRF-TOKEN, Sec-Fetch-Site and User-Agent among them, and hands each Set-Cookie back on its own.

Forwarded Headers

Laravel only knows the browser through the headers the proxy sets. Trust the proxy, and only the proxy, with $middleware->trustProxies(at: ...) naming the address Laravel sees it at, such as 127.0.0.1 when both run on one server:

PHP
// bootstrap/app.php->withMiddleware(function (Middleware $middleware) {    $middleware->trustProxies(at: '127.0.0.1');})

Laravel then reads these from the proxy:

Header Set It To Without It
X-Forwarded-For The address the request came from Keyring's rate limits count every user as one address, and the security log, devices, sessions and risk signals such as CredentialStuffing all see the proxy's.
X-Forwarded-Host The site's host The URLs in Keyring's answers, such as redirect, point at the address the proxy reaches Laravel at.
X-Forwarded-Proto and -Port The site's scheme and port Laravel takes the request for plain HTTP, its cookies go out without Secure unless SESSION_SECURE_COOKIE is set, and URLs start with http://.
X-Forwarded-Prefix /backend URLs in Keyring's answers leave the path out, so they open the frontend's pages rather than Laravel's.

Set each one, replacing whatever the browser sent. Never add to an X-Forwarded-For the browser sent: it can put any address in it, and whether Laravel ignores that then depends on exactly which hops it trusts. Laravel trusts X-Forwarded-Port by default, so set it too, or a browser can pick the port in your URLs. Take the host and scheme from the site's URL in config, rather than from the request, which is the browser's to fill in.

If a load balancer sits in front of the frontend, getRequestIP(event) is the load balancer's address. Take the browser's from the header the load balancer sets, as long as it replaces what the browser sent. The same goes for a location header such as CF-IPCountry: the proxy passes it on as it came, so only use HeaderLocator when something in front of the frontend sets it.

The prefix reaches every URL Laravel builds while it answers, url(), route() and redirect(), but not Keyring's emailed links, nor the callback URL it gives identity providers. Those are built from APP_URL, or from Keyring::linkRootUsing(), and nothing in the request. If you set linkRootUsing(), return the site's URL from config, never url('/') or request()->root(): those carry the forwarded prefix, https://example.com/backend, and a host the browser can forge. Links of your own that you email from a request, built with url() or route(), carry the prefix too.

With Next.js

A route handler does the same in Next.js. It doesn't get the connection's address, so it takes the browser's from the header that the load balancer or host in front of it sets:

TypeScript
// app/backend/[...path]/route.tsconst laravel = process.env.LARAVEL_URL! // where the proxy reaches Laravel // Set below, the connection's own, or fetch()'s to choose: never passed on// from the browser. fetch() then only asks for encodings it can decode.const dropped = [  'host', 'connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'expect', 'content-length', 'accept-encoding',  'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-port', 'x-forwarded-prefix',] async function proxy(request: Request): Promise<Response> {  // Read here, not as the module loads: `next build` loads it without the  // environment a container only gets when it starts.  const site = new URL(process.env.SITE_URL!) // https://example.com  const url = new URL(request.url)   // Accept, X-Requested-With, Cookie, X-XSRF-TOKEN and the rest, as the browser sent them.  const headers = new Headers(request.headers)   for (const name of dropped) {    headers.delete(name)  }   headers.set('x-forwarded-for', request.headers.get('x-real-ip') ?? '') // the load balancer's header  headers.set('x-forwarded-host', site.host)  headers.set('x-forwarded-proto', site.protocol.slice(0, -1))  headers.set('x-forwarded-port', site.port || (site.protocol === 'https:' ? '443' : '80'))  headers.set('x-forwarded-prefix', '/backend')   const answer = await fetch(laravel + url.pathname.replace(/^\/backend/, '') + url.search, {    method: request.method,    headers,    body: ['GET', 'HEAD'].includes(request.method) ? undefined : await request.arrayBuffer(),    redirect: 'manual', // a redirect goes to the browser, with its cookies    cache: 'no-store',  })   // Every Set-Cookie stays a header of its own. fetch() has already decoded  // the body, so its encoding and length no longer describe it.  const passed = new Headers(answer.headers)  passed.delete('content-encoding')  passed.delete('content-length')   return new Response(answer.body, { status: answer.status, statusText: answer.statusText, headers: passed })} export { proxy as DELETE, proxy as GET, proxy as HEAD, proxy as PATCH, proxy as POST, proxy as PUT }

x-real-ip stands in for whatever header your load balancer sets. The browser can send that header itself, so it's only the browser's address when the load balancer replaces whatever the browser sent. Otherwise Laravel's rate limits and security log go by an address the browser chose. Without such a load balancer there's no address to trust, so put one, or a web server, in front that sets it.

A rewrites() entry in next.config.js that points at Laravel is shorter, and passes Accept, cookies and redirects through, but gives you no say over the forwarded headers. It doesn't replace the ones the browser sent: current versions set X-Forwarded-Host from the request's Host, and pass the browser's X-Forwarded-For, -Proto, -Port and -Prefix on exactly as sent, so the browser picks the address and prefix Laravel sees. Use a rewrite only when something in front of Next.js replaces all of those headers, the prefix included.

What Changes

What changes from the rest of this guide:

  • Emailed links start at APP_URL, the site, at Keyring's paths, which are the frontend's pages, so no linkRootUsing() is needed.
  • The single sign-on callback starts there too, such as https://example.com/auth/auth/google/callback, which is the frontend's page in Signing In. Register that URL with the provider, and don't pass its path to Laravel.
  • The URLs in Keyring's answers, such as redirect, are built from the forwarded headers, so they point at https://example.com/backend/auth/.... The frontend goes by page anyway.
  • After confirming, redirect is the page whose request got the 423, since that can be the frontend's page. The same goes for a sign in that follows Keyring's signed-out 401. Any other sign in still answers home.
  • There's no CORS to set up, and SESSION_DOMAIN stays empty. Every request is same-origin, and Laravel's CSRF check passes on Sec-Fetch-Site: same-origin.
  • The relying party ID and allowed origin default to APP_URL's host and origin, which are the site's, so passkeys need no settings. They come from APP_URL or the webauthn settings alone, never from the forwarded headers. See Relying Party and Origins.
  • Sanctum's sanctum.stateful already lists APP_URL's host.
  • Set the browser package's baseUrl to https://example.com/backend. A path the package is handed, such as the url prop of the pages emailed links open, or your own /api/user, then goes through the proxy.
  • Keyring sends Clear-Site-Data: "cache", "storage" for the site with signing out, the signed-out 401, starting or stopping an impersonation, and the 409 of an impersonation that ended by itself. Each of those clears what the frontend kept in the browser's storage and cache too, so keep nothing there that has to outlive them.

Troubleshooting

Symptom Likely Cause
A request answers a redirect or HTML where you expected JSON Neither Accept nor X-Requested-With reached Laravel. Either one is enough.
Signing in works, but the next page is signed out The proxy followed a redirect, or dropped a Set-Cookie, so the browser kept the session ID the sign in replaced.
A passkey sign in fails with a 422 just after signing in or out The same: the browser holds a replaced session ID, so the passkey options weren't kept.
Every POST answers 419 Cookie, X-XSRF-TOKEN and Sec-Fetch-Site weren't passed on, the XSRF-TOKEN cookie never reached the browser, or SESSION_DOMAIN names Laravel's host.
One user's failures lock out everyone, or the security log only shows one address Laravel doesn't trust the proxy, or the proxy doesn't set X-Forwarded-For.
The security log shows addresses users don't recognise The proxy passes on the browser's X-Forwarded-For, or Laravel trusts more than the proxy.
redirect URLs start with http://, carry a port, or name Laravel's host X-Forwarded-Proto, -Port or -Host is missing, or comes from the browser.
The browser refuses to create or use a passkey APP_URL, or webauthn.relying_party.id, names Laravel's own host rather than the site.
The passkey prompt works, but Keyring refuses the answer webauthn.origins doesn't list the site's origin.
Emailed links open Laravel's address, or a 404 APP_URL is Laravel's own address, linkRootUsing() returns something built from the request, or the proxy passes Keyring's paths to Laravel.
The identity provider refuses the callback URL The URL registered with the provider isn't APP_URL, or the linkRootUsing() root, followed by Keyring's prefix and /auth/{provider}/callback.
Your own emails link to /backend/... They were built with url() or route() during a request, which carries the forwarded prefix. Build them from APP_URL.

Pages as JSON

A request for one of Keyring's pages that expects JSON, and isn't an Inertia visit, gets the page's name and props:

Terminal
GET /auth/reset-password/{token}?email=taylor@example.comAccept: application/json
JSON
{  "page": "reset-password",  "props": { "token": "...", "email": "taylor@example.com" }}

The props are the ones listed under Pages, with everything each page needs to post back: the reset token and address, an email change's token, and the expires and signature that the verification and "this wasn't me" pages post. Their url prop is a path on Laravel, without the token or signature, for the frontend to post to.

A user whose address is already verified gets the email-verified status from the verification link instead of the page, with justNow false. A page you render with a closure through Keyring::page answers JSON requests too, so that's where to change what a JSON client gets.

Where Each Answer Goes

Answers carry a redirect, a URL on Laravel or from your config. When it's one of Keyring's pages, they also carry page, its name. Your frontend goes by page when there is one, then redirect, then stays where it is:

Answer page redirect
202 challenge, after a correct password when another factor is needed challenge, or confirm for step-up The challenge page.
200 authenticated The intended URL, or home. When it completes a sign in, alerts holds its "was this you?" alerts.
423, a route needs step-up confirm The confirm page.
401 signed-out, a session Keyring ended login The login page.
401 sign-in-to-verify, an email verification link opened while signed out, where registration hides who has an account login The login page.
401 {"message": "Unauthenticated."}, Laravel's answer to a guest None. The browser package's destination() gives login for a body with only a message
403 enroll-first enrollment_url
403 change-password password_change_url
403 impersonation-refused, a refused start of an impersonation, whatever the reason
403 impersonating, refused while impersonating the user
409 not-impersonating, a stop with nobody impersonated, such as a second one from another tab impersonation.return_url. Load it in full.
409 impersonation-ended, an impersonation that ended by itself and went back to the impersonator impersonation.return_url. Load it in full.
422 with page, a sign in or step-up that ran out or used up its guesses login or confirm That page. The reason is in errors.
422 with frozen, a removal, rename or replacement while sign-in methods are frozen Stay. frozen.skip lists the factors that can make the change now. See Making a Change With an Established Key.
422 with errors.password, beginning to add a second factor Stay. Begin again with the current password as password. See The Password for a First Second Factor.
200 email-verified The intended URL, or home with ?verified=1 when the link just verified the address. justNow says which.
A status such as password-reset, registration-received or device-reported login, register, forgot-password, verify-email, challenge or confirm, when that's where it goes Where to go, when it isn't back.

Map each page name to a route of your frontend:

Page Keyring's Path A Nuxt Route
login /auth/login pages/auth/login/index.vue
register /auth/register pages/auth/register.vue
forgot-password /auth/forgot-password pages/auth/forgot-password.vue
reset-password /auth/reset-password/{token} pages/auth/reset-password/[token].vue
verify-email /auth/email/verify pages/auth/email/verify/index.vue
email-verification /auth/email/verify/{id}/{hash} pages/auth/email/verify/[id]/[hash].vue
email-change /auth/email-changes/{change}/{action}/{token} pages/auth/email-changes/[change]/[action]/[token].vue
device-report /auth/devices/{device}/report pages/auth/devices/[device]/report.vue
sign-in-link /auth/login/challenge/email-code/link pages/auth/login/challenge/email-code/link.vue
challenge /auth/login/challenge pages/auth/login/challenge/index.vue
confirm /auth/confirm pages/auth/confirm.vue

Mirroring Keyring's paths is only required for the pages emailed links open. The others may live wherever you like.

Laravel's plain 401 names no page, so send the user to your login page. The browser package's destination() does that for you, as the table above says.

Keyring only goes on to a remembered page on your own origins, and never to another site. See Where They Go Next.

After a JSON sign in or step-up, redirect is home, unless the frontend's origin is the request's own or APP_URL's. Keep the page the user was going to in the frontend, such as in a ?redirect= query on your login route, and go there on authenticated. Only follow a path that starts with a single /, since anyone can send a link with ?redirect=https://elsewhere.example. continue is never set on authenticator-added for a JSON client (see Flash Messages and Alerts).

Building the Frontend With Nuxt

Calling Laravel

Two kinds of request go to Laravel. Keyring's forms and challenges go from the browser, through the browser package's headless Vue bindings, which hold each form's state and errors and hand every answer that goes somewhere to your router. Reading, such as your own GET /api/user, can also happen while Nuxt renders on the server, and that needs a fetch of its own.

This plugin gives the app a $keyring that calls Laravel with the browser's cookies, asks for JSON, and sends the CSRF token. It sets headers with options.headers.set(), which needs ofetch 1.4 or later: Nuxt 3.14 or later, or Nuxt 4.

TypeScript
// plugins/keyring.tsimport { appendResponseHeader } from 'h3' export default defineNuxtPlugin(() => {  const config = useRuntimeConfig()  const event = useRequestEvent()   // On the server, the token is in the cookies the browser sent. In the  // browser, it's read for every request, since Laravel replaces it.  const serverToken = useCookie('XSRF-TOKEN', { readonly: true }).value   const keyring = $fetch.create({    baseURL: config.public.apiBase, // https://api.example.com    credentials: 'include',    headers: {      accept: 'application/json',      'x-requested-with': 'XMLHttpRequest',      ...(import.meta.server ? forwardedHeaders(config.public.appUrl) : {}),    },    onRequest({ options }) {      const token = import.meta.server ? serverToken : xsrfToken()       if (token) {        options.headers.set('x-xsrf-token', token)      }    },    onResponse({ response }) {      // On the server, hand the cookies Laravel set on to the browser.      if (import.meta.server && event) {        for (const cookie of response.headers.getSetCookie()) {          appendResponseHeader(event, 'set-cookie', cookie)        }      }    },  })   return { provide: { keyring } }}) function xsrfToken(): string | undefined {  const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/)   return match ? decodeURIComponent(match[1]) : undefined} // What Laravel needs from the browser's request when the Nuxt server makes// it instead: its cookies and browser, and a Referer Sanctum recognises.function forwardedHeaders(appUrl: string): Record<string, string> {  return {    ...useRequestHeaders(['cookie', 'user-agent', 'accept-language']),    referer: appUrl,  }}

$fetch throws a FetchError for any answer that isn't a 2xx, with the body as error.data. A 202 from signing in is a 2xx, so it's returned like any other answer.

A page rendered with the cookies Laravel set must never be cached and served to someone else. Don't use a swr or isr route rule on those pages, and don't let a CDN in front of Nuxt cache them. Otherwise the next visitor gets the first one's session.

The browser package makes requests of its own, with json(). Tell it where Laravel is, in a plugin that only runs in the browser:

TypeScript
// plugins/keyring-package.client.tsimport { configureRequests, configureRoutes } from '@keyringjs/keyring' export default defineNuxtPlugin(() => {  const config = useRuntimeConfig()   configureRoutes({ prefix: 'auth' })  configureRequests({ baseUrl: config.public.apiBase, csrfCookie: '/sanctum/csrf-cookie' })})

With csrfCookie set, the package fetches Sanctum's cookie before its first POST. Its helpers throw a KeyringRequestError, with status and data, not ofetch's FetchError. See Frontends on Another Origin.

The package's Vue bindings take a navigate callback, called with a Destination whenever an answer goes somewhere. Give the app one that follows Where Each Answer Goes:

TypeScript
// composables/useKeyringNavigate.tsimport type { Destination } from '@keyringjs/keyring/vue-headless' const pages: Record<string, string> = {  login: '/auth/login',  challenge: '/auth/login/challenge',  confirm: '/auth/confirm',  // ...the rest of the table above} export function useKeyringNavigate() {  const route = useRoute()   return (to: Destination) => {    // Signed in or confirmed: on to where the user was going.    if (to.status === 'authenticated') {      return navigateTo(localPath(route.query.redirect) ?? '/dashboard')    }     if (to.page && pages[to.page]) {      // Step-up, and a guest's 401, come back here afterwards. Anything      // else only carries `redirect` on, never the rest of this page's      // query, such as a signed link's `signature`.      const redirect = to.page === 'confirm' || to.httpStatus === 401 ? route.fullPath : localPath(route.query.redirect)       return navigateTo({ path: pages[to.page], query: redirect ? { redirect } : {} })    }     // enrollment_url and password_change_url, full URLs on the frontend.    if (to.redirect) {      return navigateTo(to.redirect, { external: true })    }  }} // Only a path on this site, never another site's URL. Control characters// are refused too: browsers strip a tab, so "/\t/evil.example" becomes "//evil.example".export function localPath(value: unknown): string | undefined {  return typeof value === 'string' && /^\/(?![/\\])[^\u0000-\u001f\u007f]*$/.test(value) ? value : undefined}

Signing In

The login page posts with the package's useForm(), and offers passkeys with usePasskeyLogin():

Vue
<!-- pages/auth/login/index.vue --><script setup lang="ts">import { routes, useForm, usePasskeyLogin } from '@keyringjs/keyring/vue-headless' const navigate = useKeyringNavigate()const form = useForm({ email: '', password: '', remember: false }, { navigate })const { supported, processing, error, signIn } = usePasskeyLogin({ autofill: true, remember: () => form.remember, navigate })</script> <template>  <form @submit.prevent="form.post(routes.login)">    <input v-model="form.email" type="email" autocomplete="username webauthn">    <p v-if="form.errors.email">{{ form.errors.email }}</p>    <input v-model="form.password" type="password" autocomplete="current-password">    <button :disabled="form.processing">Sign in</button>    <p v-if="form.error">{{ form.error }}</p>  </form>   <button v-if="supported" :disabled="processing" @click="signIn()">Sign in with a passkey</button>  <p v-if="error">{{ error }}</p></template>

A wrong password is a 422, and its errors land on form.errors. Other failures, such as a 419, a 429 without errors, a network failure or a timeout, land on form.error, until the next submit or form.clearErrors(). When a second factor is needed, the answer is the 202 challenge, which navigate takes to the challenge page.

When the SingleSignOn factor is registered, loadPage(routes.login) lists the identity providers in providers. Offer each with a button that calls signInWithProvider(provider.name, { remember: form.remember }). The provider sends the user back to a callback page of the frontend, at the path in Single Sign-On. That page passes the query on to Laravel and goes where the answer says:

Vue
<!-- pages/auth/auth/[provider]/callback.vue --><script setup lang="ts">import { request, routes } from '@keyringjs/keyring/vue-headless' const route = useRoute()const navigate = useKeyringNavigate()const errors = ref<Record<string, string>>({})const message = ref<string | null>(null) onMounted(async () => {  const answer = await request('GET', routes.ssoCallback(String(route.params.provider)) + location.search)  const to = answer.to  // Kept before the trip to the provider, by the login or confirm page.  const back = localPath(sessionStorage.getItem('keyring:redirect'))   errors.value = answer.errors  // A 429, a 403 or a 404 have no field errors, only a message.  message.value = answer.ok || Object.keys(answer.errors).length ? null : answer.message   if (to?.status === 'authenticated') {    sessionStorage.removeItem('keyring:redirect')     return navigateTo(back ?? '/dashboard')  }   // Step-up: `navigate` brings the user back to this callback URL to finish.  if (to?.httpStatus === 423) {    return navigate(to)  }   // A link's answers redirect to the page it started from, or `home`:  // go to your own settings page instead.  if (to && !to.page && ['authenticator-added', 'authenticator-updated', 'sso-cancelled'].includes(to.status ?? '')) {    return navigateTo('/settings/authenticators')  }   // Not back here, this callback URL's `state` is spent. The page gets the  // stored `redirect`, so it's still there once the challenge or confirm is done.  const paths: Record<string, string> = { login: '/auth/login', challenge: '/auth/login/challenge', confirm: '/auth/confirm' }   if (to?.page && paths[to.page]) {    return navigateTo({ path: paths[to.page], query: back ? { redirect: back } : {} })  }   if (to) {    await navigate(to)  }})</script> <template>  <p v-for="error in errors" :key="error">{{ error }}</p>  <p v-if="message">{{ message }}</p></template>

A sign in answers as the login form does: authenticated, the 202 challenge, or sso-cancelled naming login. A link answers authenticator-added, authenticator-updated, a 422 on provider, or the 423 of step-up. Only that 423 goes back to the callback, since its state is spent for every other answer. A confirm, challenge or login answer goes to that page, with the stored redirect in its query. A 422 on the username field names no page, so show errors on the page. On the confirm page, an sso factor component calls confirmWithProvider(challenge.props.authenticator.id).

The browser leaves the frontend for the provider, so the ?redirect= of the login and confirm pages is lost on the trip. Keep it in sessionStorage before calling signInWithProvider() or confirmWithProvider(), and use it on the callback page after authenticated.

The answer that completes a sign in, whether it's this one, the challenge's or a passkey's, carries its "was this you?" alerts. Keep them, and show them once on the page you go to:

JSON
{  "status": "authenticated",  "redirect": "https://app.example.com/dashboard",  "alerts": [    { "type": "second_factor_failed", "factor": "totp", "at": "2026-11-08T09:12:00+00:00", "ip": "198.51.100.4" }  ]}

They're flashed to the session too, for apps whose next page reads it. Don't also read that flash from your own routes, or the alerts show twice.

The challenge page loads its props from GET /auth/login/challenge, and posts the proof to POST /auth/login/challenge/{factor}. Sending a code uses POST /auth/login/challenge/{factor}/send. The package's useChallenge() does all of that once the page is mounted in the browser. The props and fields are in The Challenge Page:

Vue
<!-- pages/auth/login/challenge/index.vue --><script setup lang="ts">import { useChallenge } from '@keyringjs/keyring/vue-headless'import factors from '~/keyring/factors' const challenge = useChallenge('login', factors, { navigate: useKeyringNavigate() })</script> <template>  <p v-if="challenge.error">{{ challenge.error }}</p>  <p v-if="!challenge.props && challenge.loading">Loading…</p>   <template v-if="challenge.props">    <component :is="challenge.component" :key="`${challenge.props.factor}:${challenge.props.authenticator.id}`" :challenge="challenge" />     <label v-if="challenge.props.canTrustDevice">      <input v-model="challenge.form.trust" type="checkbox"> Don't ask again on this device    </label>     <button v-for="option in challenge.props.alternatives" :key="`${option.factor}:${option.id}`" @click="challenge.switchTo(option)">      {{ option.name }}    </button>  </template></template>

The factor map and factor components are the ones in The Challenge Page. When the sign in has run out, navigate gets the 422 that names login, with the reason in to.answer.errors. Show it on your login page.

Step-Up

A route that needs a recent verification answers with a 423 naming the confirm page. A useForm() with navigate follows it by itself. A call made with json(), or any of the package's helpers, throws a KeyringRequestError, which destination() reads:

TypeScript
import { destination, enroll } from '@keyringjs/keyring/vue-headless' const navigate = useKeyringNavigate() try {  await enroll('passkey')} catch (error: unknown) {  const to = destination(error)   if (to?.page === 'confirm') {    return navigate(to)  }   throw error}

The confirm page is the challenge page with useChallenge('confirm', factors, { navigate }), on /auth/confirm. Once confirmed, the answer is authenticated, and navigate brings the user back. See Step-Up and Handling Step-Up in JavaScript.

These pages hold a token or a signature in their URL, so the frontend has to send them with the same headers Keyring sends:

TypeScript
// nuxt.config.tsconst emailedLink = {  headers: {    'referrer-policy': 'no-referrer',    'cache-control': 'no-store',    'x-frame-options': 'DENY',  },} export default defineNuxtConfig({  routeRules: {    '/auth/reset-password/**': emailedLink,    '/auth/email/verify/**': emailedLink,    '/auth/email-changes/**': emailedLink,    '/auth/devices/**': emailedLink,    '/auth/login/challenge/email-code/link': emailedLink,  },})

no-referrer keeps the URL out of the Referer of everything the page loads, and no-store keeps it out of caches. Scripts on the page can still read the URL, so keep analytics, session replay and error reporters off these pages. The verification, email change and "this wasn't me" pages each act on one button press, so they mustn't be framed either. See Tokens in Emailed Links.

Each page posts its secret in the body, to a path without it, as on any Keyring app (see The Pages Emailed Links Open):

  • The reset page has the token in its path and the address in its query. It posts token, email, password and password_confirmation to POST /auth/reset-password.
  • The email change page posts token to POST /auth/email-changes/{change}/confirm or /revert.
  • The sign-in link page posts code to its url prop, and only has one in the browser that started the sign in. Load it as JSON first: its props say whether this browser holds the sign in (sameBrowser), with the code to post when it does, and whether the link still works (expiresAt, null once it has ended). Posting it answers as verifying does, so navigate follows it. See Signing In From the Email for what the page says in each case.
  • The verification and "this wasn't me" pages post expires and signature to their own path on Laravel. Loading the page as JSON first gets the address being verified or the device's description, and checks the link: a bad or expired signature is a 403. The verification page needs the user signed in, and answers a 401 when they aren't. Send them to sign in, then back to the link. For a user whose address is already verified, it answers with the email-verified status instead.

Where registration hides who has an account, Keyring remembers the link in the session, and signing in verifies the address. That 401 is the sign-in-to-verify status, with its message, and page set to login. Nothing is flashed for a JSON request, so keep the message from the 401 and show it on your login page yourself.

Vue
<!-- pages/auth/devices/[device]/report.vue --><script setup lang="ts">import { loadPage, useForm } from '@keyringjs/keyring/vue-headless' const route = useRoute() const { data, error } = await useAsyncData(  'device-report',  () => loadPage<{ device: string, url: string, expires: string, signature: string }>(route.fullPath),  { server: false },) // "device-reported" answers with "page": "login", which navigate follows.const form = useForm({}, { navigate: useKeyringNavigate() }) function report() {  const { url, expires, signature } = data.value!.props!   form.post(url, { transform: () => ({ expires, signature }) })}</script>

The sign-in link page loads the same way, and posts the code only where the props say this browser holds the sign in:

Vue
<!-- pages/auth/login/challenge/email-code/link.vue --><script setup lang="ts">import { loadPage, useForm } from '@keyringjs/keyring/vue-headless' const route = useRoute() const { data } = await useAsyncData(  'sign-in-link',  () => loadPage<{ code: string | null, sameBrowser: boolean, url: string | null, expiresAt: string | null }>(route.fullPath),  { server: false },) // Signed in, or on to the challenge for another factor: navigate follows it.const form = useForm({}, { navigate: useKeyringNavigate() }) function signIn() {  const { url, code } = data.value!.props!   form.post(url!, { transform: () => ({ code }) })}</script>

Load these pages in the browser (server: false), as the examples do. That keeps the link's secret out of the Nuxt server's logs, and the request comes from the user's own IP address, which their rate limit counts.

Rendering on the Server

When Nuxt renders a page on the server, its $fetch sends none of the browser's cookies, and doesn't pass the cookies Laravel sets back to the browser. The plugin above does both. Each part matters:

  • Cookies. The session cookie signs the request in, so the Nuxt server needs it from the browser. That's why SESSION_DOMAIN covers the frontend's host.
  • Cookies Laravel sets. Keyring can move a session to a new record on any request, such as when "remember me" brings a browser back, and it sets new cookies when it does. A cookie dropped on the Nuxt server leaves the browser holding a used "remember me" cookie, which ends the session the next time it's sent. See A Cookie Used Twice.
  • User agent. Keyring's SessionFingerprintChanged risk signal compares the browser a session came from with each request's. The Nuxt server's own user agent looks like the session moved to another browser.
  • Referer or Origin. Sanctum only starts the session for a request from a host in sanctum.stateful. A request from the Nuxt server has neither header unless you set one.

Even with all of that, a request from the Nuxt server comes from the server's IP address, not the user's. Keyring's rate limits count by IP address, and so do the security log, risk signals and device records. So use server-side rendering for reads, such as your own GET /api/user, and send Keyring's forms and challenges from the browser.

What Doesn't Work

  • Different sites. The frontend and Laravel must be on one site.
  • Bearer tokens and mobile apps. Pending logins and step-up live in the session, so Keyring only signs in session guards. See Known Limitations.
  • Going back after signing in, confirming or enrolling. Keyring only goes back to pages on its own origins, so keep the page the user was going to in the frontend.
  • Laravel's guest middleware. Keyring's sign-in and registration routes are only for guests. Laravel redirects a signed-in request to them, a JSON one too, rather than answering it. Check whether the user is signed in, with GET /api/user say, before showing those pages. $middleware->redirectUsersTo() changes where the redirect goes, but don't point it at the frontend. fetch() follows the redirect to the frontend's origin, which sends no CORS headers, so the request fails with a network error.
  • Clearing the browser's data on sign out. Keyring's Clear-Site-Data header only clears what the browser keeps for Laravel's origin. Clear what the frontend kept itself when signing out answers 204.
  • The Inertia helpers. The inertia, vue and react entry points need Inertia. Use vue-headless or react-headless instead, or the headless entry point with another framework. Every other helper of the package works in any frontend once configureRequests() tells it where Laravel is. See Headless Vue and React.