To implement passkeys in a web app, you add two WebAuthn ceremonies: registration, where the browser creates a key pair and your server stores the public key, and authentication, where the browser signs a one-time challenge that your server verifies. In practice you use a maintained library for the server-side verification (SimpleWebAuthn for TypeScript, py_webauthn for Python), enable autofill sign-in with conditional mediation, and design recovery for users who lose their devices. This guide walks through both ceremonies with code that type-checks against SimpleWebAuthn 14, the current major release as of November 2026.

What a passkey is, in implementation terms

A passkey is a WebAuthn discoverable credential: a public/private key pair scoped to your domain (the relying party ID), where the private key never leaves the authenticator and the credential can be found without the user typing a username first. The FIDO Alliance and passkeys.dev use "passkey" as the umbrella term. The underlying standard is the W3C Web Authentication API; Level 3 became a W3C Recommendation on August 25, 2026.

Two kinds matter for your data model:

Synced passkey Device-bound passkey
Where the private key lives Passkey provider (Apple Passwords, Google Password Manager, 1Password, etc.) syncs it across the user's devices One authenticator, usually a hardware security key
SimpleWebAuthn credentialDeviceType multiDevice singleDevice
credentialBackedUp true once synced false
Lost-device risk Low; restored with the provider account High; the key is gone with the device
Typical user Consumers Admins, regulated workforces

Store both flags. They drive your recovery prompts: a user whose only passkey is device-bound and not backed up should be nudged to add a second one.

Passkeys are phishing-resistant by construction. The browser binds every signature to the origin it is running on, so a look-alike domain can't produce a valid assertion for yours.

Choosing a server library

Don't parse CBOR attestation objects and COSE keys yourself. Use one of these:

Language Library Current version (Nov 2026) Key functions
TypeScript / Node / Deno SimpleWebAuthn @simplewebauthn/server + @simplewebauthn/browser server 14.1.0, browser 14.0.0 generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse
Python py_webauthn (webauthn on PyPI) 3.0.1 generate_registration_options, verify_registration_response, generate_authentication_options, verify_authentication_response, options_to_json_dict

What changed recently, per the SimpleWebAuthn changelog:

  • v14.0.0 raised the minimum runtime to Node 22 LTS or Deno 2.4, added ML-DSA-44/65/87 post-quantum signature support (and prefers ML-DSA-44 during registration in runtimes that support it), added sendSignal(), browserSupportsPasskeys() and getBrowserCapabilities() to the browser package, and added expectedTopOrigin to authentication verification.
  • v14.1.0 added ConvenienceMetadataService for passkey provider names and icons, and now throws SimpleWebAuthnError when expectedRPID or expectedOrigin is invalid.
  • v13.0.0 retired @simplewebauthn/types (import types from /server or /browser) and dropped attestationType: 'indirect'.

On Node 24, the default pubKeyCredParams from generateRegistrationOptions() lists ML-DSA-44 (-48) first, then Ed25519 (-8), ES256 (-7) and RS256 (-257), and Node logs an experimental-feature warning for the ML-DSA Web Crypto algorithm. Authenticators pick the first algorithm they support, so today you will mostly still get ES256. py_webauthn 3.0.0 similarly added ML-DSA verification. If post-quantum migration is on your roadmap, our post-quantum cryptography tools overview covers the wider picture.

How to implement passkeys: the server

The example uses Express 5 and express-session for brevity. Swap the in-memory maps for your database. It type-checks under tsc --strict and runs on Node 24.

Setup and data model

import express from 'express';
import session from 'express-session';
import {
  generateRegistrationOptions,
  verifyRegistrationResponse,
  generateAuthenticationOptions,
  verifyAuthenticationResponse,
  type WebAuthnCredential,
} from '@simplewebauthn/server';
import { isoBase64URL } from '@simplewebauthn/server/helpers';

const rpName = 'Example App';
const rpID = 'localhost';                  // your registrable domain in production, e.g. example.com
const origin = 'http://localhost:3000';    // exact origin the browser reports

// --- toy storage: replace with your database ---
type User = { id: string; username: string; webauthnUserID: string };
type Passkey = WebAuthnCredential & {
  userId: string;
  webauthnUserID: string;
  deviceType: 'singleDevice' | 'multiDevice';
  backedUp: boolean;
  createdAt: Date;
};
const users = new Map<string, User>([['u1', { id: 'u1', username: 'ada@example.com', webauthnUserID: '' }]]);
const passkeys = new Map<string, Passkey>(); // keyed by credential ID (base64url)

declare module 'express-session' {
  interface SessionData { userId?: string; challenge?: string }
}

const app = express();
app.use(express.json());
app.use(session({ secret: 'change-me', resave: false, saveUninitialized: true, cookie: { sameSite: 'lax' } }));

In a real schema, the passkeys table needs: credential ID (base64url, unique, indexed), public key (bytes), counter, transports, the user's WebAuthn user handle, device type, backed-up flag, created and last-used timestamps, and a user-editable label. If you ever store or debug these values by hand, a Base64 encoder/decoder helps, but remember WebAuthn uses the URL-safe base64url alphabet without padding.

Registration ceremony

Registration happens after the user is already authenticated some other way: at sign-up, after a password login, or from an account settings page.

// Registration step 1: user is already signed in (password, magic link, etc.)
app.post('/passkeys/register/options', async (req, res) => {
  req.session.userId = 'u1'; // demo only: pretend u1 is signed in
  const user = users.get(req.session.userId)!;
  const existing = [...passkeys.values()].filter((p) => p.userId === user.id);

  const options = await generateRegistrationOptions({
    rpName,
    rpID,
    userName: user.username,
    userDisplayName: user.username,
    // reuse one stable, random user handle per account
    userID: user.webauthnUserID ? isoBase64URL.toBuffer(user.webauthnUserID) : undefined,
    attestationType: 'none',
    excludeCredentials: existing.map((p) => ({ id: p.id, transports: p.transports })),
    authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
  });

  user.webauthnUserID = options.user.id; // base64url; persist it on the user row
  req.session.challenge = options.challenge;
  res.json(options);
});

// Registration step 2: verify and store the credential
app.post('/passkeys/register/verify', async (req, res) => {
  const user = users.get(req.session.userId!)!;
  try {
    const { verified, registrationInfo } = await verifyRegistrationResponse({
      response: req.body,
      expectedChallenge: req.session.challenge!,
      expectedOrigin: origin,
      expectedRPID: rpID,
    });
    if (!verified) return res.status(400).json({ error: 'not verified' });

    const { credential, credentialDeviceType, credentialBackedUp } = registrationInfo;
    passkeys.set(credential.id, {
      ...credential, // id, publicKey (Uint8Array), counter, transports
      userId: user.id,
      webauthnUserID: user.webauthnUserID,
      deviceType: credentialDeviceType,
      backedUp: credentialBackedUp,
      createdAt: new Date(),
    });
    res.json({ verified: true });
  } catch (err) {
    res.status(400).json({ error: (err as Error).message });
  } finally {
    req.session.challenge = undefined; // challenges are single-use
  }
});

Decisions worth explaining:

  • userID is a random handle, not your database ID or email. If you omit it, SimpleWebAuthn generates random bytes. Persist it on first registration and pass it back for every later registration, so all of a user's passkeys share one handle. Sending a different handle each time can make a provider treat them as different accounts.
  • residentKey: 'required' makes the credential discoverable, which is what makes it a passkey and what username-less sign-in needs.
  • excludeCredentials stops the same authenticator registering twice. The browser raises InvalidStateError instead.
  • userDisplayName defaults to an empty string. SimpleWebAuthn's docs note that an empty display name caused QR-code registration failures in Chrome up to version 127, so set it.
  • attestationType: 'none' is the right default for consumer apps. Ask for 'direct' only if you must restrict which authenticator models can register, for example FIPS-certified security keys for administrators, and then verify against the FIDO Metadata Service.

Authentication ceremony

// Authentication step 1: no username needed for discoverable credentials / autofill
app.post('/passkeys/login/options', async (req, res) => {
  const options = await generateAuthenticationOptions({ rpID, userVerification: 'preferred' });
  req.session.challenge = options.challenge;
  res.json(options);
});

// Authentication step 2: look up the credential by ID and verify the signature
app.post('/passkeys/login/verify', async (req, res) => {
  const passkey = passkeys.get(req.body.id);
  if (!passkey) return res.status(404).json({ error: 'unknown credential', credentialID: req.body.id });
  try {
    const { verified, authenticationInfo } = await verifyAuthenticationResponse({
      response: req.body,
      expectedChallenge: req.session.challenge!,
      expectedOrigin: origin,
      expectedRPID: rpID,
      credential: {
        id: passkey.id,
        publicKey: passkey.publicKey,
        counter: passkey.counter,
        transports: passkey.transports,
      },
    });
    if (!verified) return res.status(401).json({ error: 'not verified' });

    passkey.counter = authenticationInfo.newCounter;
    req.session.regenerate(() => {
      req.session.userId = passkey.userId;
      res.json({
        verified: true,
        // lets the browser prune deleted passkeys via the Signal API
        userID: passkey.webauthnUserID,
        allAcceptedCredentialIDs: [...passkeys.values()]
          .filter((p) => p.userId === passkey.userId)
          .map((p) => p.id),
      });
    });
  } catch (err) {
    res.status(400).json({ error: (err as Error).message });
  } finally {
    req.session.challenge = undefined;
  }
});

app.listen(3000, () => console.log('listening on http://localhost:3000'));

Leaving allowCredentials empty lets the browser offer any passkey the user has for your RP ID, which is what autofill needs. If you run an identifier-first flow (user types an email, then you prompt), pass that user's credentials in allowCredentials instead.

verifyAuthenticationResponse() requires user verification by default. Platform passkeys perform biometric or PIN verification, so this rarely bites. Keep that default if passkeys replace passwords outright, since without verification a passkey is only proof of possession. Also: regenerate the session ID after login, as above, and treat the signature counter as advisory. Synced passkeys often report a counter of 0.

The browser side: registration, autofill and signals

import {
  startRegistration,
  startAuthentication,
  browserSupportsWebAuthnAutofill,
  sendSignal,
  WebAuthnError,
} from '@simplewebauthn/browser';

const rpID = 'localhost';

async function postJSON<T = any>(url: string, body?: unknown): Promise<T> {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json();
  if (!res.ok) throw Object.assign(new Error(data.error ?? res.statusText), { data, status: res.status });
  return data;
}

// Called from an "Add a passkey" button on the account page
export async function registerPasskey(): Promise<void> {
  const optionsJSON = await postJSON('/passkeys/register/options');
  try {
    const attestation = await startRegistration({ optionsJSON });
    await postJSON('/passkeys/register/verify', attestation);
    alert('Passkey saved');
  } catch (err) {
    if (err instanceof WebAuthnError && err.code === 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED') {
      alert('This device already has a passkey for your account.');
    } else if (err instanceof Error && err.name === 'NotAllowedError') {
      // user cancelled or the prompt timed out: stay quiet
    } else {
      throw err;
    }
  }
}

async function finishLogin(assertion: Awaited<ReturnType<typeof startAuthentication>>) {
  try {
    const result = await postJSON<{ userID: string; allAcceptedCredentialIDs: string[] }>(
      '/passkeys/login/verify',
      assertion,
    );
    // Tell the password manager which passkeys are still valid for this account
    await sendSignal({
      signalName: 'allAcceptedCredentials',
      rpID,
      userID: result.userID,
      allAcceptedCredentialIDs: result.allAcceptedCredentialIDs,
    });
    location.assign('/dashboard');
  } catch (err: any) {
    if (err.status === 404) {
      // Server deleted this passkey: ask the provider to hide it
      await sendSignal({ signalName: 'unknownCredential', rpID, credentialID: assertion.id });
    }
    throw err;
  }
}

// Conditional UI: run on login page load. Requires an input with autocomplete="username webauthn".
export async function initPasskeyAutofill(): Promise<void> {
  if (!(await browserSupportsWebAuthnAutofill())) return;
  const optionsJSON = await postJSON('/passkeys/login/options');
  try {
    const assertion = await startAuthentication({ optionsJSON, useBrowserAutofill: true });
    await finishLogin(assertion);
  } catch (err) {
    if (err instanceof WebAuthnError && err.code === 'ERROR_CEREMONY_ABORTED') return; // superseded by a button click
    console.error(err);
  }
}

// Explicit "Sign in with a passkey" button (modal UI)
export async function signInWithPasskey(): Promise<void> {
  const optionsJSON = await postJSON('/passkeys/login/options');
  const assertion = await startAuthentication({ optionsJSON });
  await finishLogin(assertion);
}

Conditional UI (passkey autofill)

Conditional mediation (mediation: "conditional" in the raw API) lets passkeys appear in the browser's autofill dropdown on your existing username field, next to saved passwords. Users who have a passkey pick it; everyone else keeps typing. It is the lowest-friction way to roll passkeys out without redesigning the login page.

The login form needs a username input whose autocomplete attribute ends in webauthn. SimpleWebAuthn throws if it can't find one, unless you pass verifyBrowserAutofillInput: false, which is meant for inputs inside a shadow DOM:

<form id="login">
  <input type="text" name="username" autocomplete="username webauthn" required>
  <input type="password" name="password" autocomplete="current-password">
  <button type="submit">Sign in</button>
  <button type="button" id="passkey-btn">Sign in with a passkey</button>
</form>

Call initPasskeyAutofill() on page load. When the user clicks the explicit passkey button instead, SimpleWebAuthn's WebAuthnAbortService cancels the pending conditional request automatically, which is why the code ignores ERROR_CEREMONY_ABORTED.

Signal API: keeping providers in sync

WebAuthn Level 3 adds signal methods so your site can tell the passkey provider what it knows. SimpleWebAuthn 14 wraps them in sendSignal():

  • unknownCredential: sent when the server doesn't recognize a credential (the user deleted it on your account page). The provider can hide it.
  • allAcceptedCredentials: the full list of valid credential IDs for a user, sent after successful sign-in.
  • currentUserDetails: updated userName and userDisplayName after a rename.

Signals are fire-and-forget. There's no confirmation, and unsupported browsers ignore them, so never depend on them for security. They exist to stop users picking a deleted passkey from the autofill list and hitting an error.

Detecting support

browserSupportsPasskeys() checks for a user-verifying platform authenticator or cross-device (hybrid) support via getClientCapabilities(). getBrowserCapabilities() returns each WebAuthn client capability as "supported", "unsupported" or "unknown". Use them to decide whether to show "Create a passkey" prompts, not to gate sign-in.

If you run example.com and example.co.uk on one account system, a passkey registered for one RP ID won't work on the other. Related Origin Requests fix that. Host JSON at https://example.com/.well-known/webauthn, served as application/json:

{
  "origins": [
    "https://example.co.uk",
    "https://example.de"
  ]
}

Those origins can then use rpID: 'example.com', and your server should list them in expectedOrigin (it accepts an array). Clients only have to support five unique labels (the name before the public suffix, so example counts once), and passkeys.dev says no known client supports more. It's web-only. Native apps use Digital Asset Links and Associated Domains. passkeys.dev also suggests considering federation first.

Account recovery and fallback design

Passkeys move the risk from "password stolen" to "device lost". Plan for that before launch:

  1. Encourage a second passkey. After registration, if backedUp is false, prompt the user to add another passkey or a security key.
  2. Keep a recovery path at least as strong as you can manage. A verified email magic link is common for consumer apps. For high-value accounts, use recovery codes generated at enrollment or identity re-verification. If recovery is just "click an email link", your account security is only as strong as the user's inbox.
  3. Don't delete passwords on day one. Run passkeys alongside passwords and use conditional UI. Offer "go passwordless" as an opt-in once users have two passkeys or a backed-up one.
  4. Give users a passkey management page listing each passkey with its label, creation and last-used dates, and backup status, with delete and rename. Send unknownCredential and allAcceptedCredentials signals after changes.
  5. Rate-limit and alert on new-passkey registration, since adding a passkey is what an attacker does right after a successful account takeover.

If building recovery, risk scoring and admin tooling yourself sounds like a lot, managed platforms handle most of it. See our comparison of CIAM platforms. For self-hosted, our Better Auth vs Auth.js comparison looks at how each library approaches passkeys. Passkeys also fit the "verify explicitly" principle in a zero trust architecture.

Common errors when you implement passkeys

Symptom Likely cause Fix
SecurityError / ERROR_INVALID_DOMAIN Page isn't a secure context, or RP ID doesn't match the page's domain Use HTTPS (localhost is allowed in dev); set rpID to the registrable domain or a suffix of the current host
ERROR_INVALID_RP_ID rpID isn't a registrable suffix of the origin app.example.com may use example.com, never other.com
InvalidStateError / ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED Authenticator already holds a credential in excludeCredentials Expected; tell the user they're already set up
NotAllowedError User cancelled, timed out, or no matching credential Treat as a normal cancel; offer other sign-in options
Verification fails with origin mismatch expectedOrigin missing the port, or the scheme is wrong, or a related origin isn't listed Match the exact origin string, including port; pass an array for multiple
Autofill never appears Missing webauthn token in autocomplete, or the conditional request started before the input existed Fix the attribute; call after the DOM is ready
Duplicate accounts in the passkey picker Different userID per registration Persist one random user handle per account

Python equivalent with py_webauthn

The flow is identical in Python. generate_registration_options(rp_id=..., rp_name=..., user_name=..., user_id=...) returns an options object, options_to_json_dict() converts it for your JSON response, and verify_registration_response(credential=..., expected_challenge=..., expected_origin=..., expected_rp_id=...) returns the credential ID, public key and sign count to store. Authentication uses generate_authentication_options and verify_authentication_response with the stored public key and sign count. Pin webauthn>=3.0.1 to get ML-DSA verification and the stricter attestation-format parsing from the latest release.

Frequently Asked Questions

What is the difference between passkeys and WebAuthn?

WebAuthn is the W3C browser API and protocol. A passkey is a WebAuthn discoverable credential, usually synced by a passkey provider, used for passwordless sign-in. Every passkey uses WebAuthn, but not every WebAuthn credential is a passkey. A non-discoverable security-key credential used as a second factor isn't one.

Do I need attestation to implement passkeys?

Usually not. Use attestationType: 'none' for consumer apps. Attestation identifies the authenticator model, which matters only when policy limits which devices may register, such as certified hardware keys for administrators.

Can passkeys work on localhost during development?

Yes. Browsers treat http://localhost as a secure context, so rpID: 'localhost' with expectedOrigin: 'http://localhost:3000' works. In production you need HTTPS and an RP ID matching your domain.

What happens if a user loses the device with their passkey?

Synced passkeys are restored when the user signs in to their passkey provider on a new device. Device-bound passkeys are gone, so the user needs another registered passkey or your account recovery flow. Prompt users to register a second passkey when the first isn't backed up.

Should I remove passwords once passkeys are live?

Not immediately. Run both, use passkey autofill so adoption happens naturally, and let users opt in to passwordless once they have a backed-up passkey or two registered authenticators. Removing passwords early shifts load onto recovery, which is usually your weakest flow.

Which SimpleWebAuthn version should I use?

As of November 2026, @simplewebauthn/server 14.1.0 and @simplewebauthn/browser 14.0.0. Version 14 needs Node 22 or later (or Deno 2.4+) on the server and adds the Signal API helper and ML-DSA support.

Conclusion

To implement passkeys well, you need four server routes, about eighty lines of browser code, and a lot of product decisions. Use a maintained library for verification, store one random user handle per account, require discoverable credentials, and skip attestation unless policy demands it. Turn on conditional UI so passkeys appear in autofill, send signals so providers stay in sync, and design recovery before launch rather than after the first lost phone. Run passkeys alongside passwords first, measure adoption, then make passwordless the default.