Skip to content
LogoLogo

Handler.webAuthn

Creates a WebAuthn ceremony handler that manages registration and authentication flows server-side.

Mounts 5 POST endpoints under path:

  • POST {path}/register/options — Generate credential creation options
  • POST {path}/register — Verify registration and store credential
  • POST {path}/login/options — Generate credential request options
  • POST {path}/login — Verify authentication and issue a session (cookie via Set-Cookie, or { token } body when cookie: false or the request opts in via returnToken: true)
  • POST {path}/logout — Revoke the session and clear the cookie. Only mounted when session is true (the default); otherwise calls fall through as 404.

Usage

import { Handler, Kv } from 'accounts/server'
 
const handler = Handler.webAuthn({
  kv: Kv.memory(),
  origin: 'https://example.com',
  rpId: 'example.com',
})

Then plug handler into your server framework of choice:

createServer(handler.listener)              // Node.js
Bun.serve({ fetch: handler.fetch })         // Bun
Deno.serve({ fetch: handler.fetch })        // Deno
app.all('*', c => handler.fetch(c.request)) // Elysia
app.use(handler.listener)                   // Express
app.use(c => handler.fetch(c.req.raw))      // Hono
export const GET = handler.fetch            // Next.js
export const POST = handler.fetch           // Next.js

Return Type

Handler.webAuthn returns a Handler extended with a getSession helper for resolving the current session from a follow-up request:

type ReturnType = Handler & {
  getSession: (req: Request) => Promise<SessionPayload | undefined>
}

getSession

Resolves the current session from a request's session cookie or Authorization: Bearer <token> header. Returns undefined when no token is present, the token has been revoked, or the session has been disabled (session: false).

import { Handler, Kv } from 'accounts/server'
 
const handler = Handler.webAuthn({
  kv: Kv.memory(),
  origin: 'https://example.com',
  rpId: 'example.com',
})
 
// Inside another route on the same server:
app.get('/me', async (req) => {
  const session = await handler.getSession(req)
  if (!session) return new Response('unauthorized', { status: 401 })
  return Response.json({ credentialId: session.credentialId })
})

SessionPayload

type SessionPayload = {
  /** Credential ID returned by the authenticator. */
  credentialId: string
  /** Credential public key (hex). */
  publicKey: string
  /** Optional `userHandle` returned by the authenticator. */
  userId?: string | undefined
  /** Unix timestamp (seconds) when the session was issued. */
  issuedAt: number
  /** Unix timestamp (seconds) when the session expires. */
  expiresAt: number
}

The session payload is persisted in kv under session:{token} and is also the value returned by getSession.

Parameters

  • Type: boolean
  • Default: true

Whether to issue a session cookie on successful login. When false, the login response always contains { token } in the body, no Set-Cookie header is sent, logout does not clear a cookie, and getSession ignores any incoming cookie — only Authorization: Bearer <token> is honored. Use this when the SDK lives in a non-browser context or the host app already manages its own auth cookies.

cookieName

  • Type: string
  • Default: 'accounts_webauthn'

Cookie name for the session token.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com',
  : 'my_app_session', 
})

kv

  • Type: Kv
  • Required

Key-value store for challenges, credentials, and sessions. See Kv for available adapters.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(), 
  : 'https://example.com',
  : 'example.com',
})

onAuthenticate

  • Type: (params: { credentialId: string; publicKey: string; userId?: string; request: Request }) => Response | Promise<Response> | void | Promise<void>
  • Optional

Called after a successful authentication, before the session token is issued.

  • Returning a Response merges its JSON body and status onto the default login response.
  • Returning void (or a Promise<void>) leaves the default response untouched.
  • Throwing rejects the request with 401. The thrown error's message is surfaced as the response error field, the challenge is consumed, and no session is issued.
import { Handler, Kv } from 'accounts/server'
 
const handler = Handler.webAuthn({
  kv: Kv.memory(),
  origin: 'https://example.com',
  rpId: 'example.com',
  onAuthenticate: async ({ credentialId, publicKey, request }) => { 
    if (await isBlocked(credentialId)) throw new Error('credential blocked') 
  }, 
})

onRegister

  • Type: (params: { aaguid?: string; credentialId: string; name: string; publicKey: string; request: Request }) => Response | Promise<Response> | void | Promise<void>
  • Optional

Called after a successful registration. aaguid is the authenticator model identifier when reported, and name is the value passed to POST /register/options. Returning a Response merges its JSON body and status onto the default registration response. Throwing removes the new credential and surfaces as a 400 error response.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com',
  : ({ , , ,  }) => { 
    .('Registered:', , , ) 
  }, 
})

origin

  • Type: string | readonly string[]
  • Required

Expected origin(s) for WebAuthn verification (e.g. 'https://example.com').

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com', 
  : 'example.com',
})

path

  • Type: string
  • Default: ''

Path prefix for the WebAuthn endpoints.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com',
  : '/webauthn', 
})

rpId

  • Type: string
  • Required

Relying Party ID (e.g. 'example.com').

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com', 
})

session

  • Type: boolean
  • Default: true

Whether to issue a session on successful login. When false, login acts as a stateless WebAuthn verification — no token is generated, no entry is written to the kv, and no cookie is sent. The login response still carries { credentialId, publicKey, userId? }. getSession always returns undefined and the /logout route is not mounted (so it returns 404). Use this when the host application mints its own session token (e.g. a JWT inside onAuthenticate).

ttl

  • Type: { challenge?: number; session?: number }
  • Optional

TTLs in seconds for stored challenges and issued sessions.

ttl.challenge

  • Type: number
  • Default: 300 (5 minutes)

Maximum age of a challenge in seconds before it expires.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com',
  : { : 600 }, 
})

ttl.session

  • Type: number
  • Default: 86400 (24 hours)

Lifetime of an issued session in seconds. After expiry, getSession returns undefined and the kv entry is evicted by the underlying store.

import { ,  } from 'accounts/server'
 
const  = .({
  : .(),
  : 'https://example.com',
  : 'example.com',
  : { : 60 * 60 * 24 * 7 }, // 7 days
})

cors

  • Type: boolean | Cors
  • Default: true

Inherited from from.Options. CORS configuration applied to every response.

headers

  • Type: Headers | Record<string, string>
  • Optional

Inherited from from.Options. Additional headers merged onto every response.