Passkeys in Next.js in 15 minutes (App Router + SimpleWebAuthn)
By Santiago Griman (wickz) · · 4 min read
For a while now I’ve noticed more and more apps pushing passkeys. They offer one when you sign in, they nag you to turn it on… It’s not new, of course, but that’s where things are heading. And I get it: instead of typing a password you get in with your PIN, fingerprint or face, depending on the device you’re on. It saves time and, honestly, it has saved me more than once when I forgot a password.
The good news is that it’s pretty simple to add in Next.js. I built it as a small open repo with Next.js 16, React 19, Prisma and Postgres, and the code below comes from there, cut down to the parts that matter.
Install
pnpm add @simplewebauthn/server @simplewebauthn/browser
Add three variables to .env:
RP_ID=localhost # your domain, no https:// and no port
ORIGIN=http://localhost:3000 # the full origin, with port
SESSION_SECRET= # openssl rand -hex 32
The table
One user can have several passkeys (phone, laptop, YubiKey), so they go in their own table:
model Passkey {
id String @id // credential ID from the browser
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
publicKey Bytes
counter BigInt
transports String[]
createdAt DateTime @default(now())
}
Login: the two routes
The options route creates a random challenge and keeps it in a cookie for 5 minutes:
// app/api/auth/passkey/login-options/route.ts
import { NextResponse } from "next/server";
import { generateAuthenticationOptions } from "@simplewebauthn/server";
export async function POST() {
const options = await generateAuthenticationOptions({ rpID: process.env.RP_ID! });
const res = NextResponse.json(options);
res.cookies.set("auth_challenge", options.challenge, {
httpOnly: true, secure: true, sameSite: "lax", maxAge: 300,
});
return res;
}
The verify route finds the passkey by its ID, checks the signature and opens the session:
// app/api/auth/passkey/login-verify/route.ts
import { NextRequest, NextResponse } from "next/server";
import { verifyAuthenticationResponse } from "@simplewebauthn/server";
import { prisma } from "@/lib/prisma";
import { createSessionValue } from "@/lib/session";
export async function POST(req: NextRequest) {
const body = await req.json();
const expectedChallenge = req.cookies.get("auth_challenge")?.value;
if (!expectedChallenge) return NextResponse.json({ error: "Expired" }, { status: 400 });
const passkey = await prisma.passkey.findUnique({ where: { id: body.id } });
if (!passkey) return NextResponse.json({ error: "Unknown passkey" }, { status: 404 });
const { verified, authenticationInfo } = await verifyAuthenticationResponse({
response: body,
expectedChallenge,
expectedOrigin: process.env.ORIGIN!,
expectedRPID: process.env.RP_ID!,
credential: {
id: passkey.id,
publicKey: new Uint8Array(passkey.publicKey),
counter: Number(passkey.counter),
},
});
if (!verified) return NextResponse.json({ error: "Bad signature" }, { status: 401 });
await prisma.passkey.update({
where: { id: passkey.id },
data: { counter: BigInt(authenticationInfo.newCounter) },
});
const res = NextResponse.json({ ok: true });
res.cookies.delete("auth_challenge");
res.cookies.set("user_session", createSessionValue(passkey.userId), {
httpOnly: true, secure: true, sameSite: "lax", maxAge: 60 * 60 * 24 * 7,
});
return res;
}
Registration works the same way. register-options calls generateRegistrationOptions with the logged-in user’s ID and name, and register-verify calls verifyRegistrationResponse and saves registrationInfo.credential to the table. Both routes must check the session first, or anyone could attach a passkey to any account. The full files are in the repo.
The button
"use client";
import { startAuthentication } from "@simplewebauthn/browser";
export function PasskeyLoginBtn() {
async function login() {
const options = await fetch("/api/auth/passkey/login-options", { method: "POST" }).then((r) => r.json());
try {
const answer = await startAuthentication({ optionsJSON: options });
const res = await fetch("/api/auth/passkey/login-verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(answer),
});
if (res.ok) location.href = "/dashboard";
} catch (err) {
if ((err as Error).name !== "NotAllowedError") throw err; // user closed the prompt
}
}
return <button onClick={login}>Sign in with a passkey</button>;
}
startAuthentication opens the Face ID, fingerprint or PIN prompt. The register button is the same with startRegistration.
Things that break (and how to fix them)
- “The RP ID is invalid for this domain”.
RP_IDis only the domain:example.com, nothttps://example.comorlocalhost:3000. The port goes inORIGIN. - It works on localhost and fails on Vercel. Your preview URL is a different domain. Passkeys created on
my-app-git-x.vercel.appdon’t work onexample.com, and the other way round. Test on the real domain. - “Unknown passkey” after resetting the database. The phone still has the old passkey. Delete it from the device’s password manager and register again.
- The publicKey comes back as garbage. Save it as
Bytes(Buffer.from(credential.publicKey)) and read it back withnew Uint8Array(...). Don’t store it as base64 text unless you also decode it. - A default secret in the code. If
SESSION_SECREThas a fallback value in your repo, anyone who reads the repo can sign a session cookie for any user. Fail at startup if it’s missing.
Want help adding this to your app?
Passkeys are one of those features that look hard and take an afternoon once you see the flow. If you’d rather have someone else wire it into your Next.js app, this is the kind of work I do.
Frequently asked questions
What is a passkey?
It's a key pair your device creates for one site. The private key stays on the phone or laptop, locked behind Face ID, a fingerprint or the device PIN. Your server only stores the public key. There's no password to steal, and a fake login page can't use it because the key only works on your real domain.
Do I still need passwords?
Not for the login itself, but you need some way to create the account and to recover it if the user loses every device. Most sites keep email or a password as the first step and offer "add a passkey" once the user is inside. That's what this example does.
Does it work on localhost without HTTPS?
Yes. Browsers treat localhost as a secure origin, so WebAuthn works there. In production you need HTTPS, and RP_ID must be your real domain.
Why is the counter always 0?
Passkeys synced through iCloud Keychain or Google Password Manager don't use the signature counter, so they always send 0. SimpleWebAuthn accepts that. Save the value anyway, because hardware keys like a YubiKey do increase it.
Should I use NextAuth or Clerk instead?
If you already use one of them, turn on its passkey support. If your app has its own users table, the four routes in this post are all you need, and you don't add a dependency that owns your sessions.
Have a project in mind?
Tell me what you need. I usually reply within 24 hours.