Build an age gate in Next.js that asks Denmark’s AltID app to prove a visitor is 18 or older, and verify the signed result on your server.
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.
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.
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.
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.
App
Use it for
Policy ID
Accepts responses from
AltID test app
Testing your integration
pol_age_over_18_altid_test_v1
The AltID test app and the AltID app
AltID app
Real visitors
pol_age_over_18_altid_v1
The 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.
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.
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.
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:
getResult() returns the signed result, with the claims AltID disclosed and their salt.
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.
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.
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.
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.
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> );}
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.
Click Check my age with AltID, then scan the QR code with the AltID test app.
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.
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.”
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.