Adding passkeys to a React app by hand means base64url-encoding challenges, parsing CBOR attestation objects, tracking signature counters and dealing with browser quirks. I tried that once and lost a weekend to a single ArrayBuffer conversion bug. The better approach is better-auth's passkey plugin on Postgres. It handles the WebAuthn ceremony, so you write around 60 lines of glue code. This guide covers the full setup: a Hono API, Postgres storage, a React login form with passkey autofill and password fallback, and the Safari and cross-device sync problems the docs skip over.
The steps:
- Install better-auth, the passkey plugin, the Postgres driver and a small server framework.
- Configure the better-auth server with a fixed rpID, rpName and origin.
- Run the better-auth CLI migration to create the user, session and passkey tables in Postgres.
- Create a React auth client with the passkey client plugin.
- Build a login form that offers passkey autofill and keeps email and password as a fallback.
- Ask users to add a passkey right after they sign in with a password.
- Test in Safari, Chrome and on a phone using the QR-code (hybrid) flow before you ship.
What is a passkey, and why use better-auth instead of raw WebAuthn?
A passkey is a WebAuthn credential. The private key stays on the user's device or in their password manager, and your server stores only the public key. better-auth wraps SimpleWebAuthn on the server and exposes two client calls, so you never touch the raw navigator.credentials API.
Relying Party ID (rpID): the domain each passkey is bound to. Choose it once. If you change it later, every passkey your users have stops working.
If you haven't chosen an auth library yet, I compared it with the alternative in better-auth vs NextAuth. Short version: better-auth's plugin model is why passkeys take an afternoon and not a sprint.
Step 1-3: Server, Postgres and Migrations
The server needs three things: a Postgres pool, email and password enabled as the fallback, and the passkey plugin with your domain values. I use Hono here, but any framework that can pass on a Request works.
npm install better-auth @better-auth/passkey pg hono @hono/node-server
npm install -D @types/pgSince better-auth 1.4 the passkey plugin is its own package, @better-auth/passkey. On an older version you import it from better-auth/plugins/passkey. Half the Stack Overflow answers still use the old path, which is why your import fails.
// server/auth.ts
import { betterAuth } from "better-auth";
import { passkey } from "@better-auth/passkey";
import { Pool } from "pg";
export const auth = betterAuth({
database: new Pool({ connectionString: process.env.DATABASE_URL }),
emailAndPassword: { enabled: true },
trustedOrigins: [process.env.APP_ORIGIN ?? "http://localhost:5173"],
plugins: [
passkey({
rpID: process.env.PASSKEY_RP_ID ?? "localhost",
rpName: "DevToolbox Demo",
origin: process.env.APP_ORIGIN ?? "http://localhost:5173",
}),
],
});// server/index.ts
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { auth } from "./auth";
const app = new Hono();
app.on(["GET", "POST"], "/api/auth/*", (c) => auth.handler(c.req.raw));
serve({ fetch: app.fetch, port: 3000 });Now create the tables. The CLI reads your config and adds user, session, account, verification and passkey tables:
npx @better-auth/cli migrate --config server/auth.tsThe passkey table stores the public key, credential ID, counter, device type and a backedUp flag. You'll use that flag later. If you use Drizzle or Prisma, run generate instead of migrate and commit the schema it produces.
Two rules for rpID. It must be a registrable domain, not an IP address, so 127.0.0.1 fails and localhost works. In production, set it to the apex domain (example.com, not app.example.com) so passkeys keep working across subdomains. Deploying to Vercel? Preview URLs get a new hostname on every deploy, so passkeys won't work there unless you pin a custom preview domain. That cost me 20 minutes of confusing SecurityErrors.
Step 4-6: The React Side
On the client you need the auth client plus two calls: signIn.passkey() to log in and passkey.addPasskey() to register. Proxy /api to port 3000 in your Vite config so everything stays on one origin.
// src/lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
import { passkeyClient } from "@better-auth/passkey/client";
export const authClient = createAuthClient({ plugins: [passkeyClient()] });The login form below uses conditional UI, which means saved passkeys appear in the browser's autofill dropdown on the email field. This is what makes passkeys feel like a normal login. Without it, users get a separate "Sign in with passkey" button they will ignore.
// src/routes/Login.tsx
import { useEffect, useState } from "react";
import { authClient } from "../lib/auth-client";
export function Login() {
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!window.PublicKeyCredential?.isConditionalMediationAvailable) return;
PublicKeyCredential.isConditionalMediationAvailable().then((ok) => {
if (ok) void authClient.signIn.passkey({ autoFill: true });
});
}, []);
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const form = new FormData(e.currentTarget);
const { error } = await authClient.signIn.email({
email: String(form.get("email")),
password: String(form.get("password")),
});
if (error) setError(error.message ?? "Sign-in failed");
}
return (
<form onSubmit={onSubmit}>
<input name="email" type="email" autoComplete="username webauthn" />
<input name="password" type="password" autoComplete="current-password" />
<button type="submit">Sign in</button>
<button type="button" onClick={() => authClient.signIn.passkey()}>
Use a passkey
</button>
{error && <p role="alert">{error}</p>}
</form>
);
}The webauthn token must be the last value in autoComplete. Chrome accepts it in other positions. Safari does not, and the docs don't mention it.
To get people enrolled, show a prompt after a successful password sign-in. Hoping they find a settings page doesn't work:
async function enrolPasskey() {
const { error } = await authClient.passkey.addPasskey({ name: navigator.platform });
if (error?.code === "ERROR_CEREMONY_ABORTED" || error?.message?.includes("NotAllowed")) return;
if (error) console.error(error);
}A user cancelling the prompt is normal behaviour, not an error. Don't send it to Sentry or your error dashboard will fill with NotAllowedErrors. Log the real failures there: rpID mismatches and server verification errors.
Should I keep password login as a fallback?
Yes, for now. Passkeys can still fail: on a borrowed laptop, on an older Android phone without a passkey provider, or when a corporate policy blocks platform authenticators. If you go passkey-only, recovery becomes your support team's job.
Here's my approach. Keep email and password, enrol a passkey after the first password login, and make passkeys the default once a user has one. Using a magic link as the recovery route works well too, and better-auth has a plugin for it.
What breaks in Safari?
Safari blocks passkey ceremonies that don't start from a user gesture. If your click handler awaits anything before calling addPasskey() or signIn.passkey(), Safari can throw NotAllowedError and show no prompt.
- Awaits before the ceremony: no fetches, analytics calls or
setState-then-await chains before the passkey call. better-auth's own options fetch is fine. Your extra round-trip is the problem. - Conditional UI timing: start
signIn.passkey({ autoFill: true })on mount, not on input focus. Safari only shows the autofill sheet if the request is already pending. - Private browsing: passkeys from iCloud Keychain work, but anything saved in that session is gone when the window closes. Testers will report it as a bug.
- React StrictMode: the effect runs twice in dev, so the second conditional request aborts the first. You'll see an
AbortErrorin the console. It's harmless and doesn't happen in production builds.
How does cross-device passkey sync actually work?
Passkeys sync within one ecosystem: iCloud Keychain across Apple devices, Google Password Manager across Android and Chrome, and third-party managers like 1Password everywhere they're installed. They do not sync between ecosystems. For that, users rely on the QR-code hybrid flow, which needs Bluetooth on both devices.
What this means for your app:
- Allow several passkeys per account. An iPhone user with a Windows work laptop needs two. Show the list using
authClient.passkey.listUserPasskeys()and let users name and delete them. - Check the
backedUpcolumn. If it'sfalse, the passkey is tied to one device. Warn the user that losing the device means losing the passkey, and keep their password active. - Expect orphaned rows. When a user deletes a passkey from their phone, nothing tells your server. The WebAuthn Signal API (
PublicKeyCredential.signalUnknownCredential) fixes this in Chromium. Browser support elsewhere is patchy, so in practice you'll clean up stale rows by last-used date.
The Verdict
Use better-auth's passkey plugin with Postgres. Don't write the WebAuthn code yourself. Set rpID to your apex domain on day one, put webauthn last in the autocomplete attribute, keep passwords as a fallback, and test in Safari before anything else, because Chrome hides most of these mistakes. If your React app is still on an older setup, start with the modern Vite-based React setup and add this on top.
FAQs
Do passkeys work on localhost during development?
Yes. Browsers treat localhost as a secure context, so WebAuthn works over plain HTTP there. Set rpID to localhost and the origin to your Vite dev URL. Using 127.0.0.1 fails because rpID can't be an IP address.
Can I use better-auth passkeys with Next.js instead of Vite?
Yes. Mount auth.handler in an App Router route handler at app/api/auth/[...all]/route.ts. The client code stays the same. The passkey plugin doesn't depend on any framework.
What happens to passkeys if I change my domain?
They stop working. Each passkey is bound to the rpID it was created with. Before you migrate domains, make sure users have a password or magic-link fallback, then ask them to add a new passkey on the new domain.
Is passkey-only login safe for production in 2026?
It is safe, but it's risky for support. The cryptography is sound. The weak point is account recovery when someone loses their only device. Unless every user has a synced passkey, keep a password or magic-link fallback.
Why does Safari throw NotAllowedError when Chrome works fine?
Safari enforces the user-gesture requirement more strictly. If anything you await runs between the click and the passkey call, Safari treats the request as not user-initiated. Move the passkey call to the start of the handler.