Skip to content

Handle a duplicate sign-up

A person who signs up on a new device can end up with a second, empty account. Their passkey on the first device has not synced to the new one, so the new device has no passkey to sign in with, and the sign-up creates a new user ID. Keyhaw cannot tell the two users apart, since it holds no email address. Your app keeps the address, so your app can catch the second account.

Two checks do the work. The first stops the sign-up before the passkey opens, when the address already has an account. The second removes a duplicate that gets through anyway, such as one from a sign-up that raced the first check.

Your server answers whether an address has an account. Send the address in a POST body, never in a URL, since URLs end up in logs.

routes/check-email.ts
export async function POST(request: Request) {
const { email } = await request.json()
const address = email.trim().toLowerCase()
const account = await db.accounts.findByEmail(address)
return Response.json({ taken: account !== null })
}

The browser asks as the person types, and it keeps the answer for the address it asked about. The user.creating handler reads that answer without waiting, since a handler cannot await.

main.ts
import { createKeyhaw } from "keyhaw/client"
const keyhaw = createKeyhaw()
const form = document.querySelector<HTMLFormElement>("#sign-up")
const email = document.querySelector<HTMLInputElement>("#email")
const message = document.querySelector<HTMLElement>("#message")
// The last answer and the address it was for. Null while a check is pending or after one fails.
let check: { address: string; taken: boolean } | null = null
let timer: number | undefined
email?.addEventListener("input", () => {
window.clearTimeout(timer)
timer = window.setTimeout(() => void lookUp(email.value), 300)
})
async function lookUp(value: string): Promise<void> {
const address = value.trim().toLowerCase()
check = null
try {
const response = await fetch("/api/check-email", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email: address }),
})
if (!response.ok) throw new Error(`check-email answered ${response.status}`)
const { taken } = (await response.json()) as { taken: boolean }
check = { address, taken }
} catch (error) {
console.error(error)
}
}
keyhaw.on("user.creating", (event) => {
try {
if (form === null || event.form !== form || email === null) return
const address = email.value.trim().toLowerCase()
// Only a finished check that found the address free lets the passkey open
if (check?.address === address && !check.taken) return
event.preventDefault()
if (message !== null) {
message.textContent =
check?.address === address && check.taken
? "This address already has an account. Sign in with its passkey."
: "Checking this address. Try again in a moment."
}
} catch (error) {
// A handler that throws is logged and the sign-up goes on, so stop the sign-up here
event.preventDefault()
console.error(error)
}
})

A check that is still pending, or one that failed, stops the sign-up too. The person tries again rather than create a second account, so a failed check fails closed.

Checks can miss. Two sign-ups can race past the lookup, or a script can call your sign-up without the page. The passkey exists by the time your server writes the account, so the server removes the new user when the address already has an account. It does so with deleteUser from keyhaw/server, which reads KEYHAW_SECRET_KEY from the environment.

routes/account.ts
import { deleteUser, session } from "keyhaw/server"
export async function POST(request: Request) {
const user = await session(request)
if (user === null) return new Response(null, { status: 401 })
const { email } = await request.json()
const address = email.trim().toLowerCase()
// The unique index on the account's email makes the insert report whether it wrote
const written = await db.accounts.insertIfAbsent({ user_id: user.id, email: address })
if (written) return Response.json({ status: "completed" })
const { error } = await deleteUser(user.id)
if (error !== null) console.error(error.message)
return Response.json({ status: "address_taken" }, { status: 409 })
}

deleteUser removes the user and their passkeys, and none of their sessions refresh again. It fires no event, so your own records for that user need their own delete. An access token already issued keeps working until it expires, for up to 10 minutes, so do not treat that token as a sign-in after the call.

The lookup is the first line of defense, and deleteUser is the fallback for what the lookup misses. Keep both, since the lookup stops most duplicates before a passkey exists and the fallback covers the rest.