Implementation · SealGate

Passkey sign-in with Next.js (App Router): Route Handlers and autofill

4 min read

Key points

  • Passkey registration and sign-in each take two round trips (get options, sign in the browser, send to verify), and one dynamic Route Handler in Next.js can handle both.
  • Since Next.js 15, a Route Handler's params and cookies() are Promises, so await them before use.
  • Only allow registration for signed-in users, and decide signed_in from your server session, not from anything the browser sends.

To add passkey sign-in to a Next.js App Router project, handle both the options and verify requests in one Route Handler at app/api/passkey/[step]/route.ts, adding your API key to the JSON the browser SDK sends and relaying it to SealGate. When sign-in verification succeeds, issue your existing session for the returned external_id. Since Next.js 15, a Route Handler's params and cookies() are Promises, so await both. Only allow registration for signed-in users, and set signed_in from your server session.

How it fits together

Both registration and sign-in finish in two round trips:

  1. Browser: the SDK POSTs { kind: 'login' } to /api/passkey/options
  2. Route Handler: calls SealGate's POST /v1/login/options and returns challenge_id and options
  3. Browser: the person confirms with their fingerprint, face or screen lock, and the SDK sends the result to /api/passkey/verify
  4. Route Handler: calls POST /v1/login/verify and, on success, issues your session for the external_id

Only your server holds the API key; it never reaches the browser. SealGate generates WebAuthn challenges and verifies signatures, while your user data and sessions stay with you.

Before you start

  • Next.js 15 or later (App Router)
  • Create a project in the SealGate dashboard and issue a Test environment API key (it starts with sk_test_). The Test environment starts with the rp_id localhost and the allowed origin http://localhost:3000, so it works with next dev on its default port
  • Put SEALGATE_API_KEY=sk_test_... in .env.local (no NEXT_PUBLIC_ prefix, which would expose it to the browser)
  • Install the browser SDK: npm install sealgate-browser

This guide assumes your existing login has at least two functions. The names are examples:

  • getCurrentUser(): returns the signed-in user for the current request, or null
  • createSession(userId): issues a session for that user and sets the cookie

The Route Handler

Create app/api/passkey/[step]/route.ts. step is either options or verify.

ts
// app/api/passkey/[step]/route.ts
import type { NextRequest } from 'next/server';
import { createSession, getCurrentUser } from '@/lib/auth'; // your existing login

const BASE = 'https://api.sealgate.jp/v1';

async function sealgate(path: string, payload: unknown) {
  const res = await fetch(`${BASE}${path}`, {
    method: 'POST',
    headers: {
      authorization: `Bearer ${process.env.SEALGATE_API_KEY}`,
      'content-type': 'application/json',
    },
    body: JSON.stringify(payload),
  });
  return { res, json: await res.json() };
}

function bad(status: number, code: string, message: string) {
  return Response.json({ error: { code, message } }, { status });
}

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ step: string }> },
) {
  const { step } = await params; // params is a Promise in Next.js 15+
  const body = await req.json();
  if (step !== 'options' && step !== 'verify') return bad(404, 'not_found', 'Unknown step');

  if (body.kind === 'register') {
    // Registration is for signed-in users only. Decide signed_in here, never from the browser
    const user = await getCurrentUser();
    if (!user) return bad(401, 'unauthorized', 'Sign in first');

    const { res, json } =
      step === 'options'
        ? await sealgate('/register/options', {
            external_id: user.id, // an internal ID, not an email address
            display_name: user.email, // shown in the passkey dialog
            signed_in: true,
          })
        : await sealgate('/register/verify', {
            challenge_id: body.challenge_id,
            response: body.response,
            name: typeof body.name === 'string' ? body.name : undefined,
          });
    return Response.json(json, { status: res.status });
  }

  if (body.kind === 'login') {
    if (step === 'options') {
      // Without external_id, the person picks from passkeys on the device (autofill uses this too)
      const { res, json } = await sealgate('/login/options', {});
      return Response.json(json, { status: res.status });
    }
    const { res, json } = await sealgate('/login/verify', {
      challenge_id: body.challenge_id,
      response: body.response,
    });
    if (!res.ok) return Response.json(json, { status: res.status });
    await createSession(json.external_id); // from here on, it's your normal session
    return Response.json({ ok: true });
  }

  return bad(400, 'invalid_request', 'Unknown kind');
}

Three things to note:

  • Await params. In Next.js 15, a Route Handler's context.params became a Promise. Reading params.step synchronously won't give you the value.
  • Pass the registration name to verify. Whatever you pass to sg.register({ name: 'This device' }) is included in both the options and verify POSTs. SealGate's /v1/register/verify accepts name (up to 64 characters), so you can keep it as the device's label.
  • Keep the sign-in response small. The verify response also includes end_user_id and credential_id. The browser only needs to know whether sign-in worked, so this handler returns { ok: true }.

Issuing the session

Use your existing session mechanism. If it's cookie-based, await cookies() in the Route Handler as well.

ts
// lib/auth.ts (example)
import { cookies } from 'next/headers';

export async function createSession(userId: string) {
  const sessionId = await saveSession(userId); // your existing session store
  const cookieStore = await cookies();
  cookieStore.set('session', sessionId, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
  });
}

Passkey sign-in issues the same session as password sign-in. There's no need for a separate kind of session.

The sign-in page

Make the sign-in page a client component. Start waiting for autofill (conditional UI) as soon as the page renders, and offer a button too.

tsx
// app/login/passkey-login.tsx
'use client';

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { SealGate, SealGateError } from 'sealgate-browser';

const sg = new SealGate({
  optionsUrl: '/api/passkey/options',
  verifyUrl: '/api/passkey/verify',
});

export function PasskeyLogin() {
  const router = useRouter();
  const [error, setError] = useState('');

  useEffect(() => {
    let active = true;
    (async () => {
      if (!(await SealGate.conditionalMediationAvailable())) return;
      try {
        // Doesn't resolve until the person picks a passkey
        await sg.login({}, { mediation: 'conditional' });
        if (active) router.push('/dashboard');
      } catch (e) {
        if (e instanceof SealGateError && e.code === 'aborted') return;
        if (active) setError("We couldn't sign you in with a passkey.");
      }
    })();
    return () => {
      active = false;
      SealGate.abort(); // stop waiting when leaving the page
    };
  }, [router]);

  async function loginWithButton() {
    SealGate.abort(); // stop the autofill wait first
    try {
      await sg.login();
      router.push('/dashboard');
    } catch (e) {
      if (e instanceof SealGateError && (e.code === 'cancelled' || e.code === 'aborted')) return;
      setError("We couldn't sign you in with a passkey.");
    }
  }

  return (
    <div>
      <input name="username" autoComplete="username webauthn" />
      {/* keep your existing password field and sign-in button */}
      <button type="button" onClick={loginWithButton}>
        Sign in with a passkey
      </button>
      {error && <p role="alert">{error}</p>}
    </div>
  );
}
  • Autofill needs autoComplete="username webauthn" on the input. In React the attribute is autoComplete.
  • A call interrupted by SealGate.abort() fails with code: 'aborted'. That happens when switching to the button or leaving the page, so don't show it as an error.
  • cancelled means the person closed the dialog or it timed out. Keep any message low-key.

The registration screen

Put registration somewhere signed-in users can reach, such as account settings.

tsx
// app/settings/add-passkey.tsx
'use client';

import { useState } from 'react';
import { SealGate, SealGateError } from 'sealgate-browser';

const sg = new SealGate({
  optionsUrl: '/api/passkey/options',
  verifyUrl: '/api/passkey/verify',
});

export function AddPasskey() {
  const [message, setMessage] = useState('');

  async function add() {
    try {
      await sg.register({ name: 'This device' });
      setMessage('Passkey added. Next time you can sign in on this device with it.');
    } catch (e) {
      if (!(e instanceof SealGateError)) throw e;
      if (e.code === 'already_registered') setMessage('This device already has a passkey.');
      else if (e.code === 'cancelled') setMessage('');
      else setMessage("We couldn't add the passkey.");
    }
  }

  if (!SealGate.supported()) return null; // hide on browsers without passkey support
  return (
    <div>
      <button type="button" onClick={add}>Add a passkey</button>
      {message && <p role="status">{message}</p>}
    </div>
  );
}

already_registered means this authenticator already holds a passkey for this user. SealGate includes existing passkeys in excludeCredentials, so the authenticator refuses a duplicate.

For prompting people right after sign-in, see Prompting users to create a passkey after sign-in.

Before you go live

  • Set up the Live environment. Add a Live environment with your production rp_id (such as example.com) and allowed origins, and put the sk_live_ key in your production server's environment variables. See Choosing your RP ID and origins
  • CSRF protection. Apply the same protections as your existing forms (checking the Origin header, CSRF tokens) to Route Handlers that change state. Values in the SDK's extra option are sent with both the options and verify POSTs, and fetchInit lets you add headers
  • Error handling. SealGate errors look like { "error": { "code", "message" } }, and the SDK throws SealGateError with that code. On challenge_expired (challenges expire after 5 minutes) or verification_failed, let the person try again
  • Device management. Let people revoke the passkey of a lost device from settings. List the user's passkeys with GET /v1/users/{external_id}/credentials, check that the selected one is in that list, then call DELETE /v1/credentials/{credential_id}

See the docs for API details. Pricing is on the pricing table.

FAQ

Can I use Server Actions instead?

The SDK POSTs JSON to optionsUrl and verifyUrl, so a Route Handler is the natural fit.

What happens if I don't await params?

Since Next.js 15, params is a Promise. Reading params.step synchronously won't give you the expected value.

Does this work with the Pages Router?

Yes. Relay options and verify the same way from API Routes.

Sources

Related posts

Back to the blog