All Blogs
Blog

Add Passkeys to TanStack Start with Better Auth

Add passkeys to TanStack Start with Better Auth and Drizzle, including registration, passwordless sign-in, conditional UI autofill, and a password fallback.

Last updated on November 30, 2026•—

Passwords are still the most common way to sign in, but they are also the most common way accounts get stolen. Users reuse them, typo them, and fall for phishing pages that look just like ours. Passkeys fix this. They are a WebAuthn credential stored on the user's device or in a password manager, and they are unlocked with a fingerprint, a face scan, or a PIN. The private key never leaves the device, so a fake login page cannot steal it.

Better Auth ships an official passkey plugin for this, and it fits on top of the email and password setup we already have. Users can create an account with a password, add a passkey from a settings page, and then sign in with that passkey on the next visit. The password stays around as a fallback for new devices.

In this tutorial, we will learn how to add passkeys to a TanStack Start application with Better Auth and Drizzle. We will register a passkey, sign in with it (including the browser's passkey autofill), list and delete saved passkeys, and keep email and password working as a backup.

Prerequisites

This tutorial builds on the project from TanStack Start Authentication with Better Auth and Drizzle. Here's a quick recap of what we will reuse:

If you are starting from that project, you can jump straight to the plugin. If you want to follow along from scratch, complete that tutorial first.

Install the Plugin

The official passkey plugin lives in its own package, @better-auth/passkey. Let's install it:

npm install @better-auth/passkey

The plugin talks to the WebAuthn API in the browser (through SimpleWebAuthn) and stores each credential's public key in our database. We never see or store the private key.

Configure Better Auth

A passkey is bound to a relying party ID (rpID), which is the domain of our application. In local development, that value is localhost. In production, it must be our real registrable domain, such as example.com or app.example.com. Let's add it to our .env file so we can change it later without touching our code:

DATABASE_URL="postgresql://username:password@localhost:5432/mydb"
BETTER_AUTH_SECRET="your-generated-secret"
BETTER_AUTH_URL="http://localhost:3000"
BETTER_AUTH_RP_ID="localhost"

Now, let's add the plugin to our Better Auth instance. We will update src/lib/auth.ts with the following code:

src/lib/auth.ts
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@better-auth/drizzle-adapter/relations-v2';
import { tanstackStartCookies } from 'better-auth/tanstack-start';
import { passkey } from '@better-auth/passkey';
import { db } from '@/db';
import * as schema from '@/db/schema';
 
export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: 'pg',
    schema,
  }),
  emailAndPassword: {
    enabled: true,
  },
  plugins: [
    passkey({
      rpID: process.env.BETTER_AUTH_RP_ID ?? 'localhost',
      rpName: 'My App',
    }),
    tanstackStartCookies(),
  ],
});

Let's go through the new options:

By default, the plugin prefers discoverable credentials (residentKey: 'preferred') and prefers user verification (userVerification: 'preferred'). That is what we want for a passkey that can sign the user in without typing an email first.

Generate the Schema

The plugin needs a new passkey table to store each credential's public key, counter, and metadata. We will regenerate our Drizzle schema with the Better Auth CLI, the same command we used in the previous tutorial:

npx auth@latest generate --output src/db/schema.ts

The CLI will ask us if we want to overwrite the existing schema file. We can confirm it. Our user, session, account, and verification tables stay the same, and a new passkey table is added at the bottom:

src/db/schema.ts
export const passkey = pgTable(
  'passkey',
  {
    id: text('id').primaryKey(),
    name: text('name'),
    publicKey: text('public_key').notNull(),
    userId: text('user_id')
      .notNull()
      .references(() => user.id, { onDelete: 'cascade' }),
    credentialID: text('credential_id').notNull(),
    counter: integer('counter').notNull(),
    deviceType: text('device_type').notNull(),
    backedUp: boolean('backed_up').notNull(),
    transports: text('transports'),
    createdAt: timestamp('created_at'),
    aaguid: text('aaguid'),
  },
  (table) => [
    index('passkey_userId_idx').on(table.userId),
    index('passkey_credentialID_idx').on(table.credentialID),
  ],
);

Let's go through the most important fields:

The CLI also updates our Relations v2 object. The authRelations helper now includes passkey in its first argument, a passkeys: r.many.passkey(...) relation on user, and a passkey.user relation on the other side. We don't need to change src/db/index.ts, since it already passes authRelations to drizzle().

Now, let's generate a migration and apply it:

npx drizzle-kit generate
npx drizzle-kit migrate

If the Better Auth tables already exist, Drizzle Kit will create a new migration folder that only adds the passkey table and its indexes.

Add the Client Plugin

To call the new passkey methods from our React components, we need to add the client plugin to our auth client. Let's update src/lib/auth-client.ts:

src/lib/auth-client.ts
import { createAuthClient } from 'better-auth/react';
import { passkeyClient } from '@better-auth/passkey/client';
 
export const authClient = createAuthClient({
  plugins: [passkeyClient()],
});

This keeps every method we already use (signUp.email, signIn.email, signOut, useSession) and adds authClient.passkey.addPasskey, authClient.passkey.listUserPasskeys, authClient.passkey.deletePasskey, and authClient.signIn.passkey.

Register a Passkey

By default, adding a passkey requires an existing session, so we will do it from a settings page that sits behind our _protected layout. Let's create a new file called src/routes/_protected/settings.tsx. Its URL will be /settings:

src/routes/_protected/settings.tsx
import { useEffect, useState } from 'react';
import { createFileRoute, Link } from '@tanstack/react-router';
import { authClient } from '@/lib/auth-client';
 
export const Route = createFileRoute('/_protected/settings')({
  component: Settings,
});
 
function Settings() {
  const [name, setName] = useState('');
  const [passkeys, setPasskeys] = useState<
    { id: string; name?: string | null }[]
  >([]);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
 
  const loadPasskeys = async () => {
    const { data, error } = await authClient.passkey.listUserPasskeys();
 
    if (error) {
      setError(error.message ?? 'Could not load passkeys');
      return;
    }
 
    setPasskeys(data ?? []);
  };
 
  useEffect(() => {
    void loadPasskeys();
  }, []);
 
  const handleAddPasskey = async (event: React.FormEvent) => {
    event.preventDefault();
    setError(null);
    setMessage(null);
 
    const { error } = await authClient.passkey.addPasskey({
      name: name || 'My passkey',
    });
 
    if (error) {
      setError(error.message ?? 'Could not add passkey');
      return;
    }
 
    setName('');
    setMessage('Passkey added');
    await loadPasskeys();
  };
 
  const handleDelete = async (id: string) => {
    setError(null);
    setMessage(null);
 
    const { error } = await authClient.passkey.deletePasskey({ id });
 
    if (error) {
      setError(error.message ?? 'Could not delete passkey');
      return;
    }
 
    setMessage('Passkey deleted');
    await loadPasskeys();
  };
 
  return (
    <div>
      <p>
        <Link to="/dashboard">Back to dashboard</Link>
      </p>
      <h1>Passkeys</h1>
      <p>
        Passkeys let you sign in with your fingerprint, face, or a device PIN
        instead of your password.
      </p>
      <form onSubmit={handleAddPasskey}>
        <input
          placeholder="Passkey name (e.g. My laptop)"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <button type="submit">Add passkey</button>
      </form>
      {error && <p>{error}</p>}
      {message && <p>{message}</p>}
      {passkeys.length === 0 ? (
        <p>You have not added any passkeys yet.</p>
      ) : (
        <ul>
          {passkeys.map((passkey) => (
            <li key={passkey.id}>
              <span>{passkey.name || 'Passkey'}</span>
              <button type="button" onClick={() => handleDelete(passkey.id)}>
                Delete
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

When the user submits the form, addPasskey asks the server for WebAuthn registration options, the browser opens its passkey prompt, and the resulting credential is sent back to be stored in our passkey table. The optional name is just a label for our UI. If we don't pass authenticatorAttachment, the browser can offer both a platform authenticator (like Windows Hello or iCloud Keychain) and a cross-platform one (like a hardware key or a password manager).

listUserPasskeys and deletePasskey need a session, so they only work on this protected page. If you want a friendlier label when the user didn't name a passkey, Better Auth also exports getAuthenticatorName, which maps the stored aaguid to a common authenticator name.

Finally, let's add a link to this page from our dashboard:

src/routes/_protected/dashboard.tsx
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router';
import { authClient } from '@/lib/auth-client';
import { getSessionCount } from '@/lib/user.functions';
 
export const Route = createFileRoute('/_protected/dashboard')({
  loader: () => getSessionCount(),
  component: Dashboard,
});
 
function Dashboard() {
  const navigate = useNavigate();
  const { user } = Route.useRouteContext();
  const sessionCount = Route.useLoaderData();
 
  const handleSignOut = async () => {
    await authClient.signOut();
    navigate({ to: '/login' });
  };
 
  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <p>You have {sessionCount} active session(s).</p>
      <p>
        <Link to="/settings">Manage passkeys</Link>
      </p>
      <button onClick={handleSignOut}>Sign out</button>
    </div>
  );
}

If we now sign in with our password, visit /settings, and click Add passkey, the browser will prompt us to create one. To try this without a phone or a hardware key, Chrome DevTools has a WebAuthn panel (More tools > WebAuthn) where we can enable a virtual authenticator.

Sign In with a Passkey

Next, we will update our login page with a "Sign in with a passkey" button, and we will also enable conditional UI, which is the browser's passkey autofill. Conditional UI needs two things: an input with webauthn as the last value of its autocomplete attribute, and a signIn.passkey call with autoFill: true when the page mounts.

Let's update src/routes/login.tsx:

src/routes/login.tsx
import { useEffect, useState } from 'react';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { authClient } from '@/lib/auth-client';
 
export const Route = createFileRoute('/login')({
  component: Login,
});
 
function Login() {
  const navigate = useNavigate();
  const [isSignUp, setIsSignUp] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    let cancelled = false;
 
    const preloadPasskey = async () => {
      if (
        typeof window === 'undefined' ||
        !window.PublicKeyCredential ||
        !PublicKeyCredential.isConditionalMediationAvailable
      ) {
        return;
      }
 
      const available =
        await PublicKeyCredential.isConditionalMediationAvailable();
 
      if (!available || cancelled) {
        return;
      }
 
      const { data } = await authClient.signIn.passkey({ autoFill: true });
 
      if (!cancelled && data) {
        navigate({ to: '/dashboard' });
      }
    };
 
    void preloadPasskey();
 
    return () => {
      cancelled = true;
    };
  }, [navigate]);
 
  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setError(null);
 
    const { error } = isSignUp
      ? await authClient.signUp.email({ name, email, password })
      : await authClient.signIn.email({ email, password });
 
    if (error) {
      setError(error.message ?? 'Something went wrong');
      return;
    }
 
    navigate({ to: '/dashboard' });
  };
 
  const handlePasskeySignIn = async () => {
    setError(null);
 
    const { error } = await authClient.signIn.passkey();
 
    if (error) {
      setError(error.message ?? 'Something went wrong');
      return;
    }
 
    navigate({ to: '/dashboard' });
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <h1>{isSignUp ? 'Create an account' : 'Sign in'}</h1>
      {isSignUp && (
        <input
          placeholder="Name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      )}
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        autoComplete="username webauthn"
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        autoComplete="current-password webauthn"
      />
      {error && <p>{error}</p>}
      <button type="submit">{isSignUp ? 'Sign up' : 'Sign in'}</button>
      {!isSignUp && (
        <button type="button" onClick={handlePasskeySignIn}>
          Sign in with a passkey
        </button>
      )}
      <button type="button" onClick={() => setIsSignUp(!isSignUp)}>
        {isSignUp
          ? 'Already have an account? Sign in'
          : "Don't have an account? Sign up"}
      </button>
    </form>
  );
}

The "Sign in with a passkey" button starts a regular WebAuthn ceremony and does not need the email or password fields. signIn.passkey() asks the server for authentication options, the browser lets the user pick a passkey for our rpID, and Better Auth creates a session if the signature is valid.

The useEffect is the autofill path. PublicKeyCredential.isConditionalMediationAvailable() returns a Promise, so we await it and only start signIn.passkey({ autoFill: true }) when the browser supports it. If the user signs in that way, we redirect to the dashboard. If they dismiss the prompt, or if they don't have a passkey, we ignore the result and leave the password form in place. Some browsers also require a click on the email or password field before the autofill prompt appears.

Email and password still work exactly as they did before. That is important. A user who is on a new device, or who deleted their only passkey, can still sign in with their password and register a new one from the settings page. We should not remove the password until we have another recovery path (such as email magic links).

Deploy with HTTPS and the Right rpID

Passkeys only work on localhost or on HTTPS. A plain http:// deployment will fail in the browser, even if the rest of our authentication works. The rpID must also match the domain the user is visiting. If we leave it as localhost in production, or if we later change it (for example, from app.example.com to example.com), existing passkeys will stop working.

When we deploy, we will set BETTER_AUTH_URL to our public URL (for example, https://example.com) and BETTER_AUTH_RP_ID to the domain (example.com). I cover that setup, including running this stack on Cloudflare Workers, in Deploy TanStack Start to Cloudflare Workers (with Drizzle and Better Auth).

Conclusion

We have now added passkeys to our TanStack Start authentication system. Users can register a passkey from a settings page, sign in with a button or with the browser's autofill, and manage or delete the credentials we store in PostgreSQL. Email and password remain as a fallback, so a new device is never a lockout. From here, we can offer more than one passkey per user, rename them with updatePasskey, or look at Better Auth's passkey-first registration flow if we want accounts that start without a password.