To add passkey sign-in to a React app, you implement 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 and your server verifies the signature. This tutorial builds both with React, Express and the open-source SimpleWebAuthn libraries, tests them end to end with Chrome's virtual authenticator, and then covers fallback and account recovery.
Disclosure: I work at Frontegg, an auth provider. Everything before the Frontegg section uses only open-source libraries; that section shows a hosted login as one option.
What you'll build
A small app where a signed-in user adds a passkey, signs out, and signs back in with Face ID, Touch ID, Windows Hello or a phone, without typing a username.
Registration (user is already signed in)
React Express Authenticator
POST /register/options ---> new challenge, save it
startRegistration() -----------------------------> create key pair
POST /register/verify ---> check challenge, origin,
RP ID, then store public key
Authentication (signed out)
POST /login/options ---> new challenge, save it
startAuthentication() -----------------------------> sign challenge
POST /login/verify ---> check challenge, origin, RP ID,
signature, then start a session
(paths shortened from /api/passkeys/...)
Tested with Node.js 22.23, React 19.3, Vite 8.3, Express 5.3, express-session 1.19, @simplewebauthn/server 14.1 and @simplewebauthn/browser 14.0.
npm create vite@latest passkey-demo -- --template react
cd passkey-demo
npm install express express-session @simplewebauthn/server @simplewebauthn/browser
The Vite template already sets "type": "module" in package.json, so server.js can use import.
Step 1: The server
Three values tie a passkey to your site:
-
RP ID (relying party ID): your registrable domain, such as
example.com. A passkey only works on that domain and its subdomains, so pick it once. Changing it later orphans every passkey your users created. -
Origin: the exact scheme, host and port the browser reports, such as
https://app.example.com. - Challenge: a random value the server issues for each ceremony. Here it's single use and expires after 5 minutes, so a captured response can't be replayed.
The demo keeps users, passkeys and sessions in memory. /api/demo-signup stands in for your existing sign-up or password sign-in, because users should add a passkey to an account they already proved they own.
Create server.js in the project root. The setup and helpers come first:
import crypto from 'node:crypto';
import express from 'express';
import session from 'express-session';
import {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
} from '@simplewebauthn/server';
const rpName = 'Passkey demo';
const rpID = process.env.RP_ID ?? 'localhost'; // your registrable domain, e.g. example.com
const origin = process.env.ORIGIN ?? 'http://localhost:3000';
// In-memory stores so the demo runs anywhere. Use your database in production.
const users = new Map(); // userId -> { id, username }
const passkeys = new Map(); // credentialId -> { id, publicKey, counter, transports, userId }
const app = express();
app.use(express.json());
app.use(
session({
secret: process.env.SESSION_SECRET ?? 'dev-only-change-me',
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax' },
}),
);
app.use(express.static('dist'));
// Challenges are single use and expire after 5 minutes.
function saveChallenge(req, kind, value) {
req.session.challenge = { kind, value, expires: Date.now() + 5 * 60_000 };
}
function takeChallenge(req, kind) {
const c = req.session.challenge;
delete req.session.challenge;
if (!c || c.kind !== kind || Date.now() > c.expires) return null;
return c.value;
}
function requireUser(req, res, next) {
req.user = users.get(req.session.userId);
if (!req.user) return res.status(401).json({ error: 'Sign in first' });
next();
}
// Stand-in for your existing sign-up / password sign-in.
app.post('/api/demo-signup', (req, res) => {
const username = String(req.body.username ?? '').trim();
if (!username) return res.status(400).json({ error: 'Username is required' });
const id = crypto.randomUUID();
users.set(id, { id, username });
req.session.userId = id;
res.json({ username });
});
app.get('/api/me', (req, res) => {
const user = users.get(req.session.userId);
res.json(user ? { username: user.username } : null);
});
app.post('/api/signout', (req, res) => {
req.session.destroy(() => res.json({ ok: true }));
});
Registration endpoints
Add the registration routes to server.js next:
// 1. Registration ceremony: options
app.post('/api/passkeys/register/options', requireUser, async (req, res) => {
const existing = [...passkeys.values()].filter((p) => p.userId === req.user.id);
const options = await generateRegistrationOptions({
rpName,
rpID,
userName: req.user.username,
userID: new TextEncoder().encode(req.user.id),
attestationType: 'none',
excludeCredentials: existing.map((p) => ({ id: p.id, transports: p.transports })),
authenticatorSelection: { residentKey: 'required', userVerification: 'required' },
});
saveChallenge(req, 'register', options.challenge);
res.json(options);
});
// 2. Registration ceremony: verify and store the public key
app.post('/api/passkeys/register/verify', requireUser, async (req, res) => {
const expectedChallenge = takeChallenge(req, 'register');
if (!expectedChallenge) return res.status(400).json({ error: 'Challenge expired or already used' });
try {
const { verified, registrationInfo } = await verifyRegistrationResponse({
response: req.body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
});
if (!verified) return res.status(400).json({ error: 'Registration not verified' });
const { credential } = registrationInfo;
passkeys.set(credential.id, { ...credential, userId: req.user.id });
res.json({ verified: true });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
A few choices worth calling out:
-
userIDis a random UUID, not an email. The WebAuthn spec says the user handle must not contain personal information. -
residentKey: 'required'creates a discoverable credential, so the user can later sign in without typing a username. -
userVerification: 'required'asks for a biometric or device PIN. Since the passkey is the only factor here, the server also requires it (SimpleWebAuthn's verify functions default torequireUserVerification: true). -
excludeCredentialsstops the same device from registering a second passkey for the same account. -
attestationType: 'none'is the usual choice for consumer and B2B apps. You only need attestation if you must restrict which authenticator models are allowed.
Authentication endpoints
Then the sign-in routes, which end the file:
// 3. Authentication ceremony: options (no allowCredentials = discoverable passkeys)
app.post('/api/passkeys/login/options', async (req, res) => {
const options = await generateAuthenticationOptions({ rpID, userVerification: 'required' });
saveChallenge(req, 'login', options.challenge);
res.json(options);
});
// 4. Authentication ceremony: verify the signature and start a session
app.post('/api/passkeys/login/verify', async (req, res) => {
const expectedChallenge = takeChallenge(req, 'login');
if (!expectedChallenge) return res.status(400).json({ error: 'Challenge expired or already used' });
const passkey = passkeys.get(req.body.id);
if (!passkey) return res.status(400).json({ error: 'Unknown passkey' });
const userHandle = Buffer.from(req.body.response.userHandle ?? '', 'base64url').toString();
if (userHandle !== passkey.userId) return res.status(400).json({ error: 'Passkey does not match user' });
try {
const { verified, authenticationInfo } = await verifyAuthenticationResponse({
response: req.body,
expectedChallenge,
expectedOrigin: origin,
expectedRPID: rpID,
credential: passkey,
});
if (!verified) return res.status(400).json({ error: 'Sign-in not verified' });
passkey.counter = authenticationInfo.newCounter;
const user = users.get(passkey.userId);
req.session.regenerate(() => {
req.session.userId = user.id;
res.json({ username: user.username });
});
} catch (err) {
res.status(400).json({ error: err.message });
}
});
app.listen(3000, () => console.log(`Listening on ${origin}`));
Leaving allowCredentials empty lets the browser offer any passkey the user has for your RP ID. The server then looks up the credential by ID, checks that its user handle matches the stored user, verifies the signature, stores the new signature counter (SimpleWebAuthn rejects a counter that goes backwards when the authenticator uses one), and regenerates the session to avoid session fixation.
Before production, set secure: true on the session cookie, use a real SESSION_SECRET, and move sessions, users and passkeys to a persistent store.
Step 2: The React side
A tiny fetch helper in src/api.js:
export async function post(url, body) {
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 new Error(data.error ?? res.statusText);
return data;
}
The two ceremonies, plus friendlier messages for the errors users actually hit, in src/passkeys.js:
import { startRegistration, startAuthentication } from '@simplewebauthn/browser';
import { post } from './api.js';
export async function registerPasskey() {
const optionsJSON = await post('/api/passkeys/register/options');
const response = await startRegistration({ optionsJSON });
return post('/api/passkeys/register/verify', response);
}
export async function signInWithPasskey({ autofill = false } = {}) {
const optionsJSON = await post('/api/passkeys/login/options');
const response = await startAuthentication({ optionsJSON, useBrowserAutofill: autofill });
return post('/api/passkeys/login/verify', response);
}
export function friendlyError(err) {
if (err.name === 'NotAllowedError') return 'The passkey prompt was closed or timed out.';
if (err.name === 'InvalidStateError') return 'This device already has a passkey for your account.';
return err.message;
}
NotAllowedError covers a cancelled prompt, a timeout and failed user verification, so don't treat it as a server error. InvalidStateError during registration means excludeCredentials matched a passkey that's already on this device.
Replace src/App.jsx with the component:
import { useEffect, useState } from 'react';
import { browserSupportsWebAuthn, browserSupportsWebAuthnAutofill } from '@simplewebauthn/browser';
import { post } from './api.js';
import { registerPasskey, signInWithPasskey, friendlyError } from './passkeys.js';
export default function App() {
const [user, setUser] = useState(null);
const [username, setUsername] = useState('');
const [message, setMessage] = useState('');
useEffect(() => {
fetch('/api/me').then((r) => r.json()).then(setUser);
}, []);
// Conditional UI: offer passkeys in the username field's autofill menu.
// No cleanup needed: SimpleWebAuthn aborts this pending request when the
// next ceremony starts.
useEffect(() => {
if (user) return;
browserSupportsWebAuthnAutofill().then((supported) => {
if (!supported) return;
signInWithPasskey({ autofill: true })
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') setMessage(friendlyError(err));
});
});
}, [user]);
async function run(action, success) {
setMessage('');
try {
await action();
if (success) setMessage(success);
} catch (err) {
setMessage(friendlyError(err));
}
}
const passkeysSupported = browserSupportsWebAuthn();
return (
<main>
{user ? (
<>
<p>Signed in as {user.username}</p>
{passkeysSupported && (
<button onClick={() => run(registerPasskey, 'Passkey added')}>Add a passkey</button>
)}
<button onClick={() => run(async () => { await post('/api/signout'); setUser(null); })}>
Sign out
</button>
</>
) : (
<>
<input
name="username"
autoComplete="username webauthn"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<button onClick={() => run(async () => setUser(await post('/api/demo-signup', { username })))}>
Create account
</button>
{passkeysSupported ? (
<button onClick={() => run(async () => setUser(await signInWithPasskey()))}>
Sign in with a passkey
</button>
) : (
<p>This browser doesn't support passkeys. Use your usual sign-in method.</p>
)}
</>
)}
<p role="status">{message}</p>
</main>
);
}
Passkeys in the autofill menu (conditional UI)
Two details make passkeys show up in the browser's autofill list on the username field:
- The input has
autoComplete="username webauthn". - On page load, the app starts an authentication request with
useBrowserAutofill: true. That request stays pending until the user picks a passkey from autofill. If they click Sign in with a passkey instead, SimpleWebAuthn aborts the pending request, which is whyAbortErroris ignored.
For local development, build the client and let Express serve it so the origin is http://localhost:3000:
npx vite build && node server.js
If you prefer npm run dev, replace the template's vite.config.js with this one, which proxies /api to Express. Start the server with ORIGIN=http://localhost:5173 node server.js so origin checks match.
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: { proxy: { '/api': 'http://localhost:3000' } },
});
Step 3: Test it without a phone
Chrome can emulate an authenticator. In DevTools, open More tools → WebAuthn and enable the virtual authenticator environment to click through by hand. For CI, Playwright can drive the same thing through the Chrome DevTools Protocol.
Create e2e.test.mjs in the project root. It starts the server, creates a virtual authenticator, and walks through the flows:
import { spawn } from 'node:child_process';
import assert from 'node:assert/strict';
import { chromium } from 'playwright';
const server = spawn('node', ['server.js'], { stdio: 'inherit' });
for (let i = 0; ; i++) {
try { await fetch('http://localhost:3000/api/me'); break; } catch {
if (i > 50) throw new Error('server did not start');
await new Promise((r) => setTimeout(r, 100));
}
}
let browser;
try {
browser = await chromium.launch();
// A Chrome virtual authenticator: a platform authenticator with user verification.
async function newPage({ autofill }) {
const context = await browser.newContext();
if (!autofill) {
// The virtual authenticator answers autofill requests instantly, so turn
// conditional UI off when we want to test the button path.
await context.addInitScript(() => {
PublicKeyCredential.isConditionalMediationAvailable = async () => false;
});
}
const page = await context.newPage();
page.errors = [];
page.on('pageerror', (e) => page.errors.push(e.message));
const cdp = await context.newCDPSession(page);
await cdp.send('WebAuthn.enable');
const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', {
options: {
protocol: 'ctap2',
transport: 'internal',
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
automaticPresenceSimulation: true,
},
});
return { page, cdp, authenticatorId };
}
const statusIs = (page, text) =>
page.waitForFunction((t) => document.querySelector('[role=status]').textContent.includes(t), text);
let pass = 0;
const ok = (name) => { pass++; console.log('PASS', name); };
const { page, cdp, authenticatorId } = await newPage({ autofill: false });
let lastLoginBody;
page.on('request', (req) => {
if (req.url().endsWith('/api/passkeys/login/verify')) lastLoginBody = req.postData();
});
await page.goto('http://localhost:3000');
await page.fill('input[name=username]', 'alice');
await page.click('text=Create account');
await page.waitForSelector('text=Signed in as alice');
ok('demo sign-up');
await page.click('text=Add a passkey');
await statusIs(page, 'Passkey added');
const { credentials } = await cdp.send('WebAuthn.getCredentials', { authenticatorId });
assert.equal(credentials.length, 1);
assert.equal(credentials[0].isResidentCredential, true);
ok('registration stores 1 discoverable credential');
await page.click('text=Add a passkey');
await statusIs(page, 'already has a passkey');
ok('excludeCredentials blocks a second passkey on the same device');
await page.click('text=Sign out');
await page.click('text=Sign in with a passkey');
await page.waitForSelector('text=Signed in as alice');
ok('button sign-in with a discoverable passkey (no username typed)');
// Same browser session, same signed assertion: the challenge was already used.
const replay = await page.request.post('http://localhost:3000/api/passkeys/login/verify', {
data: JSON.parse(lastLoginBody),
});
assert.equal(replay.status(), 400);
ok(`replayed assertion rejected: ${(await replay.json()).error}`);
await page.click('text=Sign out');
await page.click('text=Sign in with a passkey');
await page.waitForSelector('text=Signed in as alice');
ok('second sign-in (counter updated)');
await page.click('text=Sign out');
await cdp.send('WebAuthn.setUserVerified', { authenticatorId, isUserVerified: false });
await page.click('text=Sign in with a passkey');
await statusIs(page, 'closed or timed out');
ok('failed user verification shows a friendly error');
// Conditional UI: same passkey on a second "device" with autofill enabled.
// Copy the credential with its current signature counter.
const { credentials: [current] } = await cdp.send('WebAuthn.getCredentials', { authenticatorId });
const b = await newPage({ autofill: true });
await b.cdp.send('WebAuthn.addCredential', { authenticatorId: b.authenticatorId, credential: current });
await b.page.goto('http://localhost:3000');
await b.page.waitForSelector('text=Signed in as alice');
ok('conditional UI (autofill) sign-in');
assert.deepEqual([...page.errors, ...b.page.errors], []);
ok('no page errors');
console.log(`${pass}/9 passed`);
} finally {
await browser?.close();
server.kill();
}
One gotcha: the virtual authenticator answers conditional UI requests instantly, so on a page with autofill enabled the user is signed in before your test can click anything. The init script in newPage() switches autofill off for the button-path tests, and a second context with autofill on covers conditional UI. It copies the credential with its current signature counter; a stale copy is rejected, which is the counter check doing its job.
The replay check posts the same signed response again from the same browser session, so the 400 shows a captured response can't be reused, even in the same browser session. Run it:
npm i -D playwright
npx playwright install chromium
npx vite build && node e2e.test.mjs
Output:
PASS demo sign-up
PASS registration stores 1 discoverable credential
PASS excludeCredentials blocks a second passkey on the same device
PASS button sign-in with a discoverable passkey (no username typed)
PASS replayed assertion rejected: Challenge expired or already used
PASS second sign-in (counter updated)
PASS failed user verification shows a friendly error
PASS conditional UI (autofill) sign-in
PASS no page errors
9/9 passed
Fallback and account recovery
A passkey lives on a device or in a password manager, and either can be lost. Plan for that before you ship:
- Keep the existing sign-in method while users adopt passkeys. Show the passkey button next to it, not instead of it.
- Offer passkey creation right after a successful sign-in with another method, when you know who the user is. That's what the Add a passkey button does here.
-
Store several passkeys per user. The
passkeysmap is keyed by credential ID, so a laptop and a phone can each have one. Give users a page to list and delete them (not shown in the demo). - Make recovery at least as strong as sign-in. If a lost passkey can be replaced through an email link alone, the email link is your real security level. Re-verify with a second factor, then prompt for a new passkey.
-
Check support before you show the button.
browserSupportsWebAuthn()handles old browsers; fall back to the normal form when it returnsfalse.
Option: passkeys with a hosted login (Frontegg)
If you'd rather not run the WebAuthn server yourself, a hosted login can do the ceremonies for you. In Frontegg, passkeys are a setting in the login box, and the React SDK redirects to the hosted login. The passkeys guide on frontegg.com covers the B2B side, such as SSO users, tenant policies and recovery; here's the code side.
- In the Frontegg builder, open the login box tab and turn on the Passkeys toggle. The sign-in page then shows a Sign in with passkey button, and users are prompted to set up a passkey at their next login.
- Enable and publish the Privacy & Security page of the self-service portal. That's where users manage or delete their passkey.
- Wire up the React SDK. Passkeys need
@frontegg/react5.0.28 or later; I tested this with 7.20.2 in a fresh Vite app, separate from the self-hosted demo:
npm create vite@latest frontegg-passkeys -- --template react
cd frontegg-passkeys
npm install @frontegg/react react-router-dom
src/frontegg.js, with the values from your Frontegg environment:
export const contextOptions = {
baseUrl: 'https://[YOUR_SUBDOMAIN].frontegg.com',
appId: '[YOUR_APP_ID]',
};
src/main.jsx:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { FronteggProvider } from '@frontegg/react';
import { contextOptions } from './frontegg.js';
import App from './App.jsx';
createRoot(document.getElementById('root')).render(
<StrictMode>
<FronteggProvider
contextOptions={contextOptions}
hostedLoginBox={true}
authOptions={{ keepSessionAlive: true }}
>
<App />
</FronteggProvider>
</StrictMode>,
);
src/App.jsx:
import { useAuth, useLoginWithRedirect } from '@frontegg/react';
import { contextOptions } from './frontegg.js';
export default function App() {
const { user, isAuthenticated } = useAuth();
const loginWithRedirect = useLoginWithRedirect();
if (!isAuthenticated) {
// The hosted login box shows "Sign in with passkey" once the Passkeys toggle is on.
return <button onClick={() => loginWithRedirect()}>Sign in</button>;
}
return (
<>
<p>Signed in as {user?.name}</p>
{/* Users add or delete their passkey under Privacy & Security in the self-service portal. */}
<a href={`${contextOptions.baseUrl}/oauth/portal`}>Manage passkeys</a>
</>
);
}
Add your callback URL (for example http://localhost:5173/oauth/callback) under Authentication → Login Method and your app's domain under Keys & Domains → Domains → Allowed origins.
Limits to know before you turn it on:
- Each user can register one passkey per device. To replace it, they delete the old one under Privacy & Security.
- The Passkeys toggle requires SMS or Authenticator app as an MFA option. Users whose MFA method is a built-in authenticator or security key don't see the passkey prompt.
- Users who sign in with SSO aren't offered passkeys. They keep signing in through their identity provider.
- Frontegg recommends setting up a custom domain before enabling passkeys in production.
Checklist
- [ ] Pick the RP ID (your registrable domain) once and keep it stable.
- [ ] Issue a fresh challenge per ceremony; make it single use with a short expiry.
- [ ] Verify origin, RP ID, challenge and signature on the server, never in the browser.
- [ ] Use a random user handle, not an email.
- [ ] Require user verification if the passkey is the only factor.
- [ ] Use discoverable credentials and add
webauthnto the username field'sautocomplete. - [ ] Handle
NotAllowedErrorandInvalidStateErrorwith clear messages. - [ ] Test with a virtual authenticator in CI.
- [ ] Keep a fallback sign-in method and a recovery path at least as strong as sign-in.
- [ ] Give users a way to list and delete their passkeys.
Further reading: the W3C WebAuthn Level 3 spec, passkeys.dev for enrollment patterns, and the SimpleWebAuthn docs.
Top comments (1)
This is the most complete passkey walkthrough I have read in a while — and the part I will steal is the replay test. Posting the same signed response twice and expecting a 400 is the signature counter doing its job in public, and most tutorials never show the check at all.
One thing I would want to see before copying the demo's shape into anything real: the demo keeps users, passkeys and sessions in memory, which means a server restart wipes the stored signature counters. Would the replay check still hold after a restart — a response replayed against a fresh counter store — or does the counter check only work while the process lives? Same question for the 5-minute single-use challenges, really. That is the line between "the check exists" and "the check survives the thing it is guarding against." How would you harden that if you moved the store to Postgres?