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:

  • userID is 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 to requireUserVerification: true).
  • excludeCredentials stops 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(fri...
Source:https://dev.to/ciam_michay/add-passkey-sign-in-to-a-react-app-2can