AltID is the Danish Agency for Digital Government’s identity app. When your site needs to know that a Danish visitor is 18 or older, you can ask AltID instead of asking for a birth date. The visitor scans a QR code or taps a link, AltID asks them to share “over 18”, and your server reads a signed result. In this guide you’ll build an age gate in a Next.js app: a page that shows a QR code or an Open AltID link, a server route that verifies the signed result, and an 18+ page that opens only after AltID confirms the visitor is over 18. Every call to Authbound runs on your server, so the same calls work from any Node.js backend. The finished app is the nextjs-altid-age-check example.

Before you start

  • A Next.js app that uses the App Router and the default @/ import alias. The code in this guide is written for Next.js 16.
  • A test secret key (sk_test_...). Create one on your project’s API Keys page in the Authbound dashboard, or use the key you received when your access was set up.
  • A phone with the AltID test app or the AltID app. See Choose an AltID app.
Don’t have access yet? Contact us. Age verification with AltID doesn’t require you to register with the Danish Agency for Digital Government. Requests for other data do, and aren’t covered here.

Choose an AltID app

There are two AltID apps, and each has a built-in policy. The policy decides which app the wallet handoff opens, and which app’s responses Authbound accepts. The wallet handoff is the QR code or link that opens the app. Built-in policies work in every project with no setup.
AppUse it forPolicy IDAccepts responses from
AltID test appTesting your integrationpol_age_over_18_altid_test_v1The AltID test app and the AltID app
AltID appReal visitorspol_age_over_18_altid_v1The AltID app only
Start with the test policy. Your own AltID app also works with a test key, under either policy, so you can test with your own AltID app before you go live. The AltID policy rejects responses from the AltID test app. To get the AltID test app, contact us.

1. Install the SDK

pnpm add @authbound/server qrcode
pnpm add -D @types/qrcode
@authbound/server makes the calls to Authbound from your server. qrcode draws the QR code in the browser.

2. Add your keys

.env.local
AUTHBOUND_SECRET_KEY=sk_test_...
AUTHBOUND_API_URL=https://sandbox.authbound.io
AUTHBOUND_ALTID_POLICY_ID=pol_age_over_18_altid_test_v1
AGE_CHECK_COOKIE_SECRET=replace-with-32-random-bytes
Generate AGE_CHECK_COOKIE_SECRET with openssl rand -base64 32. Your server uses it to sign the cookie that records a passed verification. AUTHBOUND_API_URL is required. Test keys use https://sandbox.authbound.io, which accepts test keys only. You switch to your live API URL when you go live. Keep the secret key on the server. This flow doesn’t need a publishable key, because the browser only talks to your own routes.

3. Start a verification

Create lib/altid.ts. It holds every call to Authbound, and you’ll add to it in the next two steps. The first block imports everything the file needs. Create the verification with provider: "eudi", the provider Authbound uses for AltID. AltID returns its response with unencrypted direct_post, so set responseMode to match.
lib/altid.ts
import {
  AuthboundClient,
  AuthboundClientError,
  ResultTokenVerificationError,
  verifyClaimsDigest,
} from "@authbound/server";

export type AgeCheckState =
  | "pending"
  | "over_18"
  | "not_over_18"
  | "declined"
  | "failed"
  | "expired"
  | "canceled"
  | "result_invalid";

export function requiredEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is required`);
  return value;
}

let client: AuthboundClient | undefined;

function authbound(): AuthboundClient {
  client ??= new AuthboundClient({
    apiKey: requiredEnv("AUTHBOUND_SECRET_KEY"),
    apiUrl: requiredEnv("AUTHBOUND_API_URL"),
  });
  return client;
}

const VERIFICATION_ID_PATTERN = /^vrf_[A-Za-z0-9]{8,64}$/;

export function isVerificationId(value: string): boolean {
  return VERIFICATION_ID_PATTERN.test(value);
}

/** Pass your user's ID when visitors sign in, so a webhook can find whose check it was. */
export async function startAgeCheck(customerUserRef?: string) {
  const verification = await authbound().verifications.create({
    policyId: requiredEnv("AUTHBOUND_ALTID_POLICY_ID"),
    customerUserRef,
    provider: "eudi",
    // AltID answers only unencrypted direct_post.
    providerOptions: { eudi: { responseMode: "direct_post" } },
  });

  // The AltID link: encode it in a QR code on desktop, or open it on the phone.
  const walletUrl = verification.clientAction?.data;
  if (!walletUrl?.startsWith("https://")) {
    throw new Error("The verification has no AltID link");
  }

  return {
    verificationId: verification.id,
    walletUrl,
    expiresAt:
      verification.clientAction?.expiresAt ?? verification.expiresAt ?? null,
  };
}
clientAction.data on the new verification is the wallet handoff: an https:// link that opens AltID. The page encodes it in a QR code on a computer, and opens it directly on a phone.

4. Read the signed result

Add readAgeCheck() to lib/altid.ts. While AltID hasn’t responded, a verification’s status is created, awaiting_user, awaiting_provider or processing, which this function reports as pending. A verification ends as verified, failed, canceled or expired.
lib/altid.ts
export async function readAgeCheck(
  verificationId: string
): Promise<{ state: AgeCheckState; customerUserRef: string | null }> {
  const verification = await authbound().verifications.get(verificationId);
  const customerUserRef = verification.customerUserRef ?? null;
  switch (verification.status) {
    case "verified":
      return { state: await readAgeOutcome(verificationId), customerUserRef };
    case "failed":
      return {
        state:
          verification.failureCode === "user_declined" ? "declined" : "failed",
        customerUserRef,
      };
    case "expired":
    case "canceled":
      return { state: verification.status, customerUserRef };
    default:
      return { state: "pending", customerUserRef };
  }
}

/**
 * `verified` means AltID sent a valid answer, and "not over 18" is a valid
 * answer too. Only the signed claim value decides.
 */
async function readAgeOutcome(verificationId: string): Promise<AgeCheckState> {
  const result = await authbound().verifications.getResult(verificationId);
  if (result.status !== "verified" || !result.claims || !result.claimsSalt) {
    return "result_invalid";
  }

  try {
    // Checks the signature against /v1/jwks, plus the issuer, subject and expiry.
    const token = await authbound().verifications.verifyResultToken(
      result.resultToken,
      {
        verificationId,
      }
    );
    if (token.payload.status !== "verified") return "result_invalid";
    // Checks that the claims are the ones the signed token commits to.
    if (!(await verifyClaimsDigest(result.claims, result.claimsSalt, token))) {
      return "result_invalid";
    }
  } catch (error) {
    if (error instanceof ResultTokenVerificationError) return "result_invalid";
    throw error;
  }

  const ageProof = result.claims["eu.europa.ec.av.1"] as
    | Record<string, unknown>
    | undefined;
  if (ageProof?.age_over_18 === true) return "over_18";
  if (ageProof?.age_over_18 === false) return "not_over_18";
  return "result_invalid";
}
When a verification is verified, readAgeOutcome() checks the signed result before it trusts it:
  1. getResult() returns the signed result, with the claims AltID disclosed and their salt.
  2. verifyResultToken() checks the signature, issuer, subject and expiry against the keys published by your AUTHBOUND_API_URL. A signed result from the test environment never verifies in production.
  3. verifyClaimsDigest() checks that the claims are the ones the signed result commits to.
AltID returns the age proof under the eu.europa.ec.av.1 namespace, the EU’s age verification credential, so the function reads claims["eu.europa.ec.av.1"].age_over_18.
Treat the visitor as 18 or older only when age_over_18 is true. A verified status means AltID sent a valid response, and “under 18” is a valid response too.
The claims are readable for 15 minutes after the verification ends, so read them when it finishes and store the outcome you need. The signed result itself is valid for one hour from when you read it.

5. Cancel an open verification

Add cancelAgeCheck() to the end of lib/altid.ts. It ignores 409, which means the verification already ended.
lib/altid.ts
export async function cancelAgeCheck(verificationId: string): Promise<void> {
  try {
    await authbound().verifications.cancel(verificationId);
  } catch (error) {
    // 409: the check already finished, so there is nothing to cancel.
    if (error instanceof AuthboundClientError && error.statusCode === 409)
      return;
    throw error;
  }
}

6. Tie each verification to the visitor

A verification’s result must count only for the visitor who started it. Otherwise someone could reuse another person’s “over 18”. So the browser never sends a verification ID. When a verification starts, your server keeps its ID in an HttpOnly cookie, and reads and cancels only that verification. When the signed result says over 18, the server sets a second, signed cookie, and your pages gate on that.
lib/age-session.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";
import { isVerificationId, requiredEnv } from "@/lib/altid";

/** The visitor's open check. The browser never sends a verification ID itself. */
const CHECK_COOKIE = "altid_check";
/** Set by the server only after it has verified a signed "over 18" answer. */
const OVER_18_COOKIE = "age_over_18";
const CHECK_MAX_AGE_SECONDS = 30 * 60;
const OVER_18_MAX_AGE_SECONDS = 24 * 60 * 60;

const cookieOptions = {
  httpOnly: true,
  sameSite: "lax",
  secure: process.env.NODE_ENV === "production",
  path: "/",
} as const;

function sign(value: string): string {
  return createHmac("sha256", requiredEnv("AGE_CHECK_COOKIE_SECRET"))
    .update(value)
    .digest("base64url");
}

export async function rememberCheck(verificationId: string): Promise<void> {
  (await cookies()).set(CHECK_COOKIE, verificationId, {
    ...cookieOptions,
    maxAge: CHECK_MAX_AGE_SECONDS,
  });
}

export async function currentCheck(): Promise<string | null> {
  const verificationId = (await cookies()).get(CHECK_COOKIE)?.value;
  return verificationId && isVerificationId(verificationId)
    ? verificationId
    : null;
}

export async function forgetCheck(): Promise<void> {
  (await cookies()).delete(CHECK_COOKIE);
}

export async function rememberOver18(verificationId: string): Promise<void> {
  const expiresAt = Math.floor(Date.now() / 1000) + OVER_18_MAX_AGE_SECONDS;
  const value = `${verificationId}.${expiresAt}`;
  (await cookies()).set(OVER_18_COOKIE, `${value}.${sign(value)}`, {
    ...cookieOptions,
    maxAge: OVER_18_MAX_AGE_SECONDS,
  });
}

/** Gate 18+ content on this, never on what the browser says. */
export async function isOver18(): Promise<boolean> {
  const [verificationId, expiresAt, signature] =
    (await cookies()).get(OVER_18_COOKIE)?.value.split(".") ?? [];
  if (!(verificationId && expiresAt && signature)) return false;

  const expected = Buffer.from(sign(`${verificationId}.${expiresAt}`));
  const actual = Buffer.from(signature);
  if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
    return false;
  return Number(expiresAt) > Date.now() / 1000;
}
The verification cookie lasts 30 minutes, longer than a verification’s default lifetime of 15 minutes, so it never expires while AltID can still respond. The “over 18” cookie lasts 24 hours. If your app already has sessions, keep the verification ID and the outcome in the session instead of in these two cookies.

7. Add the API route

One route starts, reads and cancels the visitor’s verification. It returns the state as one word, never claims or the signed result.
app/api/age-check/route.ts
import {
  currentCheck,
  forgetCheck,
  rememberCheck,
  rememberOver18,
} from "@/lib/age-session";
import { cancelAgeCheck, readAgeCheck, startAgeCheck } from "@/lib/altid";

export const dynamic = "force-dynamic";

const noStore = { "cache-control": "no-store" };

/** Starts a check, replacing any open one, and ties it to this browser. */
export async function POST() {
  const previous = await currentCheck();
  if (previous) await cancelAgeCheck(previous);

  const { verificationId, walletUrl, expiresAt } = await startAgeCheck();
  await rememberCheck(verificationId);
  return Response.json(
    { walletUrl, expiresAt },
    { status: 201, headers: noStore }
  );
}

/** The state of this browser's check, as one word. Never claims or tokens. */
export async function GET() {
  const verificationId = await currentCheck();
  if (!verificationId) {
    return Response.json(
      { error: "no_check" },
      { status: 404, headers: noStore }
    );
  }

  const { state } = await readAgeCheck(verificationId);
  if (state === "over_18") await rememberOver18(verificationId);
  if (state !== "pending") await forgetCheck();
  return Response.json({ state }, { headers: noStore });
}

/** Cancels this browser's open check. */
export async function DELETE() {
  const verificationId = await currentCheck();
  if (verificationId) await cancelAgeCheck(verificationId);
  await forgetCheck();
  return new Response(null, { status: 204 });
}
The page starts a verification, shows a QR code on a computer or an Open AltID link on a phone, and polls your route every 2 seconds until AltID responds.
app/page.tsx
"use client";

import QRCode from "qrcode";
import { useEffect, useState } from "react";
import type { AgeCheckState } from "@/lib/altid";

type AgeCheck = { walletUrl: string; expiresAt: string | null };

const POLL_INTERVAL_MS = 2000;

const MESSAGES: Record<Exclude<AgeCheckState, "pending">, string> = {
  over_18: "AltID confirmed that you are 18 or older.",
  not_over_18: "AltID answered that you are under 18.",
  declined: "You declined the request in AltID.",
  failed: "The check failed. Start again.",
  expired: "The check expired. Start again.",
  canceled: "The check was canceled.",
  result_invalid: "The answer could not be checked. Start again.",
};

function isPhone(): boolean {
  return /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent);
}

export default function AgeCheckPage() {
  const [check, setCheck] = useState<AgeCheck | null>(null);
  const [state, setState] = useState<AgeCheckState | null>(null);
  const [qrCode, setQrCode] = useState<string | null>(null);
  const [phone, setPhone] = useState(false);

  useEffect(() => setPhone(isPhone()), []);

  // The server cancels any open check before it starts a new one.
  async function start() {
    setCheck(null);
    setQrCode(null);
    setState(null);

    const response = await fetch("/api/age-check", { method: "POST" });
    if (!response.ok) {
      setState("failed");
      return;
    }
    const started = (await response.json()) as AgeCheck;
    setCheck(started);
    setState("pending");
    setQrCode(
      await QRCode.toDataURL(started.walletUrl, { margin: 1, width: 240 })
    );
  }

  async function cancel() {
    await fetch("/api/age-check", { method: "DELETE" });
    setCheck(null);
    setState("canceled");
  }

  useEffect(() => {
    if (!check || state !== "pending") return;
    let stopped = false;
    let inFlight = false;
    let timer: ReturnType<typeof setTimeout> | undefined;

    async function poll() {
      if (stopped || inFlight) return;
      inFlight = true;
      clearTimeout(timer);
      let next: AgeCheckState = "pending";
      try {
        const response = await fetch("/api/age-check", { cache: "no-store" });
        if (response.ok)
          next = ((await response.json()) as { state: AgeCheckState }).state;
      } catch {
        // A failed read is retried on the next tick.
      }
      inFlight = false;
      if (stopped) return;
      if (next === "pending") timer = setTimeout(poll, POLL_INTERVAL_MS);
      else setState(next);
    }

    // Phones pause timers while AltID is in front, so check at once on return.
    function onVisible() {
      if (document.visibilityState === "visible") poll();
    }

    document.addEventListener("visibilitychange", onVisible);
    timer = setTimeout(poll, POLL_INTERVAL_MS);
    return () => {
      stopped = true;
      clearTimeout(timer);
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, [check, state]);

  return (
    <main
      style={{
        fontFamily: "system-ui, sans-serif",
        margin: "4rem auto",
        maxWidth: 420,
      }}
    >
      <h1>Age check</h1>
      <button onClick={start} type="button">
        {check ? "Start again" : "Check my age with AltID"}
      </button>

      {check && state === "pending" ? (
        <>
          {phone ? (
            <p>
              <a href={check.walletUrl}>Open AltID</a>
            </p>
          ) : (
            <>
              <p>Scan the code with AltID on your phone.</p>
              {qrCode ? (
                <img
                  alt="AltID QR code"
                  height={240}
                  src={qrCode}
                  width={240}
                />
              ) : null}
            </>
          )}
          <button onClick={cancel} type="button">
            Cancel
          </button>
        </>
      ) : null}

      {state && state !== "pending" ? <output>{MESSAGES[state]}</output> : null}
      {state === "over_18" ? (
        <p>
          <a href="/adult">Continue to 18+ content</a>
        </p>
      ) : null}
    </main>
  );
}
Phones pause timers while AltID is in front, so the page also polls as soon as the visitor comes back to the browser. Start again and Cancel both cancel the open verification, so an abandoned one doesn’t stay open until it expires.

9. Gate your content

Decide on the server, from the signed cookie. Never trust what the browser says about the outcome.
app/adult/page.tsx
import { redirect } from "next/navigation";
import { isOver18 } from "@/lib/age-session";

export const dynamic = "force-dynamic";

export default async function AdultPage() {
  if (!(await isOver18())) redirect("/");

  return (
    <main
      style={{
        fontFamily: "system-ui, sans-serif",
        margin: "4rem auto",
        maxWidth: 420,
      }}
    >
      <h1>18+ content</h1>
      <p>
        Your server checked a signed AltID answer before it showed this page.
      </p>
    </main>
  );
}

10. Test your integration

  1. Start your app with pnpm dev and open http://localhost:3000. You don’t need a public URL: AltID responds to Authbound, and your page polls your own server.
  2. Click Check my age with AltID, then scan the QR code with the AltID test app.
  3. Approve the request in AltID and return to the browser. The page shows “AltID confirmed that you are 18 or older.” and a Continue to 18+ content link.
  4. Follow the link. /adult shows the 18+ page. In a private window, /adult redirects to /.
To see a failure, respond with the AltID test app while AUTHBOUND_ALTID_POLICY_ID is pol_age_over_18_altid_v1. The verification ends as failed with issuer_untrusted or presentation_invalid, and the page shows “The check failed. Start again.”

What each outcome means

StatusFailure codeClaimMeaningWhat to do
verifiedage_over_18: trueThe visitor is 18 or older.Let them in. The route sets the signed cookie.
verifiedage_over_18: falseThe visitor is under 18.Keep the content closed.
faileduser_declinedThe visitor declined in AltID.Offer to start again.
failedpresentation_invalid or issuer_untrustedThe response didn’t pass verification, for example a response from the AltID test app under the AltID policy.Check that the policy matches the app.
failedAny other codeThe verification failed.Start a new verification.
canceledYour server canceled the verification.Start a new one if the visitor asks.
expiredNobody responded within the verification’s lifetime, 15 minutes by default.Start a new verification.

Optional: receive webhooks

Polling is all this page needs. If you also want your server notified when a verification ends, for example to record the outcome against a signed-in user, add an endpoint on your project’s Webhooks page in the Authbound dashboard. Webhooks and results shows the route that verifies each event’s signature. To know whose verification ended, pass your user’s ID to startAgeCheck() in the POST route. Authbound stores it as customerUserRef. A verification ends with a verification.completed, verification.failed, verification.canceled or verification.expired event. When one arrives, call readAgeCheck() with event.data.object.id. It returns the outcome together with that customerUserRef, and for a completed verification it verifies the signed result first. Webhooks never carry claims, so always read the outcome with readAgeCheck() before you change anything.

Troubleshooting

SymptomCauseFix
The page shows “The check failed. Start again.” at once. The server log shows AUTHBOUND_API_URL is required or a similar error.A variable is missing from .env.local.Set all four variables and restart the dev server.
The page shows “The check failed. Start again.” at once, and the server log shows an AuthboundClientError with status 401 (invalid_api_key).The key and AUTHBOUND_API_URL are for different environments, for example a live key on https://sandbox.authbound.io.Use a test key with https://sandbox.authbound.io, and a live key with your live API URL.
The verification fails with issuer_untrusted or presentation_invalid.You responded with the AltID test app under pol_age_over_18_altid_v1.Use pol_age_over_18_altid_test_v1 while testing, or respond with the AltID app.
The page stays on the QR code or link after you approve on the phone.The visitor hasn’t returned to the browser, and the phone paused the page’s timers.Switch back to the browser tab. The page polls as soon as it’s visible.
/adult redirects to / after a passed verification.The “over 18” cookie expired after 24 hours, or AGE_CHECK_COOKIE_SECRET changed.Run the verification again.

Go live

You receive a live secret key (sk_live_...) together with your live API URL. Don’t have them yet? Contact us.
  1. Replace the test key with your live secret key.
  2. Set AUTHBOUND_API_URL to your live API URL.
  3. Set AUTHBOUND_ALTID_POLICY_ID to pol_age_over_18_altid_v1, so only responses from the AltID app are accepted.
  4. Generate a new AGE_CHECK_COOKIE_SECRET for production.
  5. Run one verification with your own AltID app before you send visitors to it.

Next steps

Webhooks and results

Verify webhook signatures and keep signed results as evidence.

How it works

See how a verification moves from your server to the wallet and back.

Policies

See the built-in policies and create your own.