Add a clickwrap to a Next.js and Supabase app
Seven files put terms and privacy acceptance on your signup page: a server action creates the session, your own checkbox and button collect the acceptance, and Supabase creates the user only after your server has confirmed the record.
Free plan: 10 live signatures a month and a full test mode. No card required.
The working code: a signup clickwrap in the App Router
Copy the seven files into a Next.js App Router project that uses Supabase for authentication. One install covers the packages they import: npm install esigncomply @esigncomply/browser @esigncomply.
// app/signup/actions.ts "use server"; import { cookies, headers } from "next/headers"; import { esc } from "@/lib/esigncomply"; import { supabaseAdmin } from "@/lib/supabase-admin"; import { confirmRecord, saveAcceptance } from "@/lib/esign-confirm"; const INCONCLUSIVE = "We could not confirm whether your acceptance was recorded. Please wait while we check."; // Creates the session with the secret key and returns only the client token. export async function startSignupCeremony(input: { email: string; country: string; state?: string }) { const signerId = crypto.randomUUID(); // your identifier for this person. Keep using it for them in later sessions. const country = input.country.toUpperCase(); // from the form, never from an IP address const h = await headers(); const origin = h.get("origin") ?? `https://${h.get("host")}`; const { data: session, error } = await esc.sessions.create( { profile: process.env.ESIGNCOMPLY_PROFILE_ID!, signer: { external_id: signerId, email: input.email, class: "consumer", country, region: country === "US" && input.state ? `US-${input.state.toUpperCase()}` : undefined, }, documents: [ { document: process.env.ESIGNCOMPLY_TERMS_ID!, version: "current" }, { document: process.env.ESIGNCOMPLY_PRIVACY_ID!, version: "current" }, ], context: { url: `${origin}/signup`, locale: "en-US", purpose: "account_signup" }, }, { idempotencyKey: `signup-${signerId}` }, ); if (error) return { ok: false as const, message: error.message }; // Server-owned state: the signer and the versions this session pinned. const saved = await supabaseAdmin.from("acceptances").insert({ signer_id: signerId, session_id: session.id, document_version_ids: session.documents.map((d) => d.version_id), }); if (saved.error) return { ok: false as const, message: "We could not start the signup. Try again." }; // The browser gets an httpOnly pointer to that row and the client token. Never the key. (await cookies()).set("esc_ceremony", session.id, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", maxAge: 60 * 60, path: "/", }); return { ok: true as const, clientToken: session.client_token, apiUrl: session.api_url, termsVersionId: session.documents[0].version_id, privacyVersionId: session.documents[1].version_id, }; } // Confirms the record with the secret key, then creates the account. export async function finishSignup(form: FormData, recordId: string) { const sessionId = (await cookies()).get("esc_ceremony")?.value; if (!sessionId) return { ok: false as const, message: "Your signup session has ended. Start again." }; // The record ID came from the browser: a claim to check. const confirmed = await confirmRecord({ recordId: String(recordId), sessionId }); if (!confirmed.ok) return { ok: false as const, message: INCONCLUSIVE }; // not confirmed: no account const { data: created, error } = await supabaseAdmin.auth.admin.createUser({ email: String(form.get("email")), password: String(form.get("password")), }); if (error || !created.user) return { ok: false as const, message: "We could not create your account. Try again." }; await saveAcceptance(confirmed.acceptanceId, confirmed.record, created.user.id); return { ok: true as const }; }
// app/signup/signup-form.tsx "use client"; import { useEffect, useRef, useState } from "react"; import { EsignComplyError, useCeremony, useDocument, type Ceremony } from "@esigncomply/react"; import { finishSignup, startSignupCeremony } from "./actions"; type Started = Extract<Awaited<ReturnType<typeof startSignupCeremony>>, { ok: true }>; const INCONCLUSIVE = "We could not confirm whether your acceptance was recorded. Please wait while we check."; const LINK = "text-blue-600 underline"; // underlined, and a colour that stands out from the text around it export function SignupForm({ company }: { company: string }) { const formRef = useRef<HTMLFormElement>(null); const assentRef = useRef<HTMLDivElement>(null); const checkboxRef = useRef<HTMLInputElement>(null); const submitRef = useRef<HTMLButtonElement>(null); const active = useRef(false); // a session exists or is being created const run = useRef(0); const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const [started, setStarted] = useState<Started | null>(null); const [watched, setWatched] = useState<Ceremony | null>(null); const [pending, setPending] = useState(false); const [message, setMessage] = useState<string | null>(null); // The hooks attach to the session and report each document link. const { ceremony, status, error, canComplete } = useCeremony({ clientToken: started?.clientToken, apiUrl: started?.apiUrl }); const terms = useDocument<HTMLAnchorElement>(ceremony, { versionId: started?.termsVersionId, mode: "hyperlink" }); const privacy = useDocument<HTMLAnchorElement>(ceremony, { versionId: started?.privacyVersionId, mode: "hyperlink" }); const watching = ceremony !== null && watched === ceremony; // Start once the email is valid, when the signer leaves a field. Not on submit. async function start() { clearTimeout(timer.current); const form = formRef.current; if (!form || active.current) return; const data = new FormData(form); const email = String(data.get("email") ?? ""); if (!/^\S+@\S+\.\S+$/.test(email)) return; active.current = true; const current = ++run.current; const res = await startSignupCeremony({ email, country: String(data.get("country") ?? ""), state: String(data.get("state") ?? "") }); if (current !== run.current) return; // a field changed while the request was in flight if (res.ok) setStarted(res); else { active.current = false; setMessage(res.message); } } // A session belongs to the email, country and state it was created with. // When one of them changes, or the session expires, drop it at once. function drop() { if (!active.current) return; run.current += 1; // a start that is still in flight is ignored active.current = false; if (checkboxRef.current) checkboxRef.current.checked = false; // a new session must find the box unchecked setStarted(null); setMessage(null); } // Start a new session when the field is left (the form's onBlur), or when the typing stops. function onSignerChange(event: React.ChangeEvent<HTMLInputElement>) { drop(); clearTimeout(timer.current); if (event.target.name !== "email") timer.current = setTimeout(() => void start(), 800); // an email is finished when its field is left } // Watch the notice, the checkbox and the button once both links are reported. useEffect(() => { if (!ceremony || !terms.presented || !privacy.presented) return; ceremony .observeAssent({ region: assentRef.current, checkbox: checkboxRef.current, submit: submitRef.current }) .then(() => setWatched(ceremony), () => undefined); // a failure arrives in `error` }, [ceremony, terms.presented, privacy.presented]); const expired = error?.code === "client_token_expired"; useEffect(() => { if (!expired) return; drop(); void start(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [expired]); async function onSubmit(event: React.FormEvent<HTMLFormElement>) { event.preventDefault(); if (!ceremony) return; const form = new FormData(event.currentTarget); setPending(true); setMessage(null); try { const result = await ceremony.complete(); // the signing act: { recordId, receipt, verifyUrl, status } // The server confirms the record with the secret key before it creates the account. const outcome = await finishSignup(form, result.recordId); if (outcome.ok) window.location.assign("/app"); else setMessage(outcome.message); } catch (err) { // A refusal carries a message and a fix: keep the form. Anything else is inconclusive. const refused = err instanceof EsignComplyError && err.code !== "network_error" && err.status < 500; setMessage(refused ? err.message : INCONCLUSIVE); } finally { setPending(false); } } const alert = message ?? (expired ? null : error?.message); return ( <form ref={formRef} onSubmit={onSubmit} onBlur={() => void start()}> <label> Email <input name="email" type="email" autoComplete="email" required onChange={onSignerChange} /> </label> <label> Country <input name="country" defaultValue="US" maxLength={2} required onChange={onSignerChange} /> </label> <label> State <input name="state" placeholder="CA" maxLength={2} onChange={onSignerChange} /> </label> <label> Password <input name="password" type="password" autoComplete="new-password" required minLength={12} /> </label> <div ref={assentRef}> {/* Unchecked, and disabled until the SDK is watching it. Nothing here ever sets it to checked. */} <input ref={checkboxRef} id="agree" type="checkbox" disabled={!watching} /> <label htmlFor="agree"> By checking the box and clicking Create account, you agree to the{" "} <a ref={terms.ref} href={started ? `/legal/terms?v=${started.termsVersionId}` : "/legal/terms"} target="_blank" rel="noopener" className={LINK}> Terms of Service </a>{" "} and acknowledge the{" "} <a ref={privacy.ref} href={started ? `/legal/privacy?v=${started.privacyVersionId}` : "/legal/privacy"} target="_blank" rel="noopener" className={LINK}> Privacy Notice </a> . </label> <button ref={submitRef} type="submit" disabled={pending || !(canComplete || status === "completed")}> Create account </button> <p> {company} uses Esign Comply to record this event on its behalf. See {company}'s Privacy Notice for purposes and roles. </p> </div> {alert ? <p role="alert">{alert}</p> : null} </form> ); } // app/signup/page.tsx renders it: // export default function SignupPage() { return <SignupForm company="Acme" />; }
// lib/esign-confirm.ts import "server-only"; import { esc } from "@/lib/esigncomply"; import { supabaseAdmin } from "@/lib/supabase-admin"; const SEALED = new Set(["recorded", "timestamped", "anchored"]); // Server confirmation: read the record with the secret key and compare it with // what this server saved when it created the session. export async function confirmRecord(input: { recordId: string; sessionId: string }) { const { data: acceptance } = await supabaseAdmin .from("acceptances") .select("id, signer_id, document_version_ids") .eq("session_id", input.sessionId) .is("user_id", null) .maybeSingle(); if (!acceptance || !input.recordId) return { ok: false as const, reason: "no_ceremony" }; const { data: record, error } = await esc.records.get(input.recordId); if (error) return { ok: false as const, reason: error.code }; // a made-up ID returns not_found const actual = record.documents.map((d) => d.version_id).sort(); const expected = [...(acceptance.document_version_ids as string[])].sort(); const ok = SEALED.has(record.status) && record.livemode === (process.env.VERCEL_ENV === "production") && record.signer.external_id === acceptance.signer_id && actual.length === expected.length && actual.every((v, i) => v === expected[i]); return ok ? { ok: true as const, acceptanceId: acceptance.id as string, record } : { ok: false as const, reason: "record_mismatch" }; } // Store the record ID and the signed receipt next to the user. export async function saveAcceptance( acceptanceId: string, record: { id: string; receipt?: string | null; signed_at: string }, userId?: string, ) { return supabaseAdmin .from("acceptances") .update({ record_id: record.id, receipt: record.receipt, accepted_at: record.signed_at, ...(userId ? { user_id: userId } : {}), }) .eq("id", acceptanceId); }
-- supabase/migrations/20261122000000_acceptances.sql create table public.acceptances ( id uuid primary key default gen_random_uuid(), -- Written when the session is created. signer_id uuid not null, -- signer.external_id sent to Esign Comply session_id text not null unique, -- ses_... document_version_ids text[] not null, -- the versions the session pinned -- Filled in once the record is confirmed. user_id uuid references auth.users (id) on delete cascade, record_id text unique, -- rec_... receipt text, -- signed receipt (JWS, ES256) accepted_at timestamptz, -- the record's signed_at created_at timestamptz not null default now() ); alter table public.acceptances enable row level security; create policy "read own" on public.acceptances for select using (auth.uid() = user_id); -- No insert, update or delete policies. Only the service role writes.
// app/legal/[slug]/page.tsx import { notFound } from "next/navigation"; import { esc } from "@/lib/esigncomply"; const DOCUMENTS: Record<string, string | undefined> = { terms: process.env.ESIGNCOMPLY_TERMS_ID, privacy: process.env.ESIGNCOMPLY_PRIVACY_ID, }; // /legal/terms?v=dv_... serves one registered version, unmodified. export default async function LegalPage({ params, searchParams, }: { params: Promise<{ slug: string }>; searchParams: Promise<{ v?: string }>; }) { const { slug } = await params; const { v } = await searchParams; const documentId = DOCUMENTS[slug]; if (!documentId) notFound(); const { data, error } = await esc.documents.versions.getContent(documentId, v ?? "current"); if (error || !data?.html) notFound(); // The registered HTML and nothing else inside the article: the SDK hashes its text. return ( <main> <article data-esc-document={data.version_id} lang={data.language} dangerouslySetInnerHTML={{ __html: data.html }} /> </main> ); }
// app/api/esigncomply/webhook/route.ts import { esc } from "@/lib/esigncomply"; import { supabaseAdmin } from "@/lib/supabase-admin"; import { saveAcceptance } from "@/lib/esign-confirm"; type Completed = { record_id: string; session_id: string; signer_external_id: string; documents: Array<{ version_id: string }> }; export async function POST(request: Request) { const rawBody = await request.text(); // the raw body, before anything parses it const { data: event, error } = await esc.webhooks.verify<Completed>( rawBody, request.headers, process.env.ESIGNCOMPLY_WEBHOOK_SECRET!, ); if (error) return new Response("Invalid signature", { status: 400 }); // Deliveries are at-least-once. This only fills in a row that is still open, so a repeat changes nothing. if (event.type === "record.completed") { const { data: acceptance } = await supabaseAdmin .from("acceptances") .select("id, signer_id, document_version_ids") .eq("session_id", event.data.session_id) .is("record_id", null) .maybeSingle(); const versions = event.data.documents.map((d) => d.version_id).sort(); const matches = acceptance && event.livemode === (process.env.VERCEL_ENV === "production") && event.data.signer_external_id === acceptance.signer_id && JSON.stringify(versions) === JSON.stringify([...(acceptance.document_version_ids as string[])].sort()); if (matches) { const { data: record } = await esc.records.get(event.data.record_id); // the payload carries no receipt if (record) await saveAcceptance(acceptance.id, record); } } return new Response(null, { status: 200 }); // also for event types this code does not know }
// lib/esigncomply.ts import "server-only"; // the build fails if a client component imports this file import { EsignComply } from "esigncomply"; export const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!); // lib/supabase-admin.ts import "server-only"; import { createClient } from "@supabase/supabase-js"; export const supabaseAdmin = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!, { auth: { persistSession: false, autoRefreshToken: false } }, );
What each file does
Seven files, four jobs: create the session on the server, collect the acceptance in your own form, confirm the record before the account exists, and keep the receipt next to the user.
startSignupCeremony runs on the server once the email is entered. It makes a signer ID, calls esc.sessions.create with your profile and both documents at version current, and saves one row in acceptances with the signer ID and the version IDs the session pinned. The browser gets the client token, the API URL and the two version IDs. The session ID goes into an httpOnly cookie, and the secret key never leaves the server.
finishSignup runs after the signing act. The record ID it receives came from the browser, so it is a claim: the action hands it to confirmRecord and calls supabaseAdmin.auth.admin.createUser only when the record checks out. Then it writes the user ID, the record ID and the signed receipt onto the row.
A client component in which every element is yours. useCeremony attaches to the session, useDocument reports each document link, and observeAssent watches the container that holds the notice, the links, the checkbox and the one primary button. The button opens when canComplete is true: the signing act is the only step left.
The checkbox starts unchecked and stays disabled until the SDK is watching it, so every tick is one the SDK saw happen. A session belongs to the email, country and state it was created with: editing one of them drops the session at once and starts a new one. ceremony.complete() runs from the real click and returns the record ID, which goes straight to finishSignup.
confirmRecord reads the record with the secret key (GET /v1) and compares it with the row your server saved. The status is recorded, timestamped or anchored. livemode matches the deployment. The signer ID is the one you made. The set of document versions is exactly the set the session pinned. A made-up record ID returns not_found, and a test record never passes in production.
saveAcceptance stores the record ID, the signed receipt (a compact ES256 token) and the accepted time. Esign Comply keeps the sealed record. Your table keeps the pointer to it and the receipt, next to the user.
The migration: one acceptances table with row-level security
supabase/migrations/20261122000000_acceptances.sqlView the file One row per ceremony. The first three columns are written when the session is created and are the server-owned state the confirmation compares against. The others are filled in when the record is confirmed. Row-level security is on with a single policy: a signed-in user reads their own rows, and only the service role writes.
A row that never gets a record ID is a signup that was started and abandoned. Sessions expire after 30 minutes, so open rows older than a day are safe to delete.
app/legal /[slug] /page.tsx: the registered version, unmodified
app/legal/[slug]/page.tsxView the file The links in the notice point here with the pinned version ID (?v=dv_...). The page fetches that exact version from Esign Comply and renders the returned HTML inside <article data-esc-document>. The browser SDK reads this page behind the link, hashes the article's text and reports it, and the API compares the hash with the registered version (rule CR-08). The legal text never lives in your repository, so the page and the record cannot drift apart.
The webhook route: the backstop when the tab closes
app/api/esigncomply/webhook/route.tsView the filerecord.completed is sent once a record is sealed. The route reads the raw body, verifies the signature with esc.webhooks.verify and fills in the open row for that session if finishSignup never ran. It only fills a row that is still open, so a repeated delivery changes nothing.
To receive test deliveries on localhost, create a test endpoint in the dashboard and run npx esigncomply webhooks listen --forward http:/.
lib/esigncomply.ts and lib/supabase-admin.ts: two server-only clients
lib/esigncomply.ts and lib/supabase-admin.tsView the file Both files import server-only, so the build fails if a client component ever imports the secret key or the service-role key. Server SDK calls return { data, error } and never throw: check error every time, as the files above do.
Run it
From an empty account to a sealed test record on localhost. No domain, no card and no deploy.
- 01
Create a free account and a test key
Sign up, then choose Create test key in the dashboard. The key starts with
esc_test_and is shown once. The Free plan needs no card, and test keys work onlocalhoston any port with no domain. - 02
Register your two documents and a signup profile
In the dashboard, add a document named Terms of Service and one named Privacy Notice, publish a version of each, and create a profile with method
checkboxand levelL1. The names matter: the notice in the form names each document by its title, and ruleCR-02looks for both. Copy the three IDs. - 03
Set the environment variables
Add these to
.env.local, and to the Vercel project for Preview and Development. None of the names starts withNEXT_PUBLIC_..env.localESIGNCOMPLY_API_KEY=esc_test_us_... # the test key, shown once in the dashboard ESIGNCOMPLY_PROFILE_ID=prof_signup_4f1a # the signup profile: checkbox, L1 ESIGNCOMPLY_TERMS_ID=doc_8Hq2 # Terms of Service ESIGNCOMPLY_PRIVACY_ID=doc_Pv71 # Privacy Notice ESIGNCOMPLY_WEBHOOK_SECRET=whsec_... # only for the webhook route SUPABASE_SERVICE_ROLE_KEY=...
- 04
Apply the migration and start the app
supabase db pushapplies the migration to your linked Supabase project. Then start the dev server.$supabase db push && npm run dev - 05
Sign up once
Open
http:/. Enter an email and move to the next field: the checkbox unlocks when the session is attached. Tick it and click Create account./localhost:3000 /signup - 06
Open the test record
The dashboard lists one new test record under Records. It shows what Esign Comply observed from the browser (the page attached, both documents presented, the notice captured, the tick, the signing act), the conformance findings and the evidence report, watermarked TEST. Your
acceptancesrow holds the same record ID and its signed receipt. - 07
Run the conformance check
The command reads
ESIGNCOMPLY_API_KEYfrom your shell and takes test keys only. It opens your page in headless Chromium at 390 by 844, 768 by 1024 and 1440 by 900, tries to submit without the tick and with a scripted click, then signs up for real at each size, so expect three test users in your development database. Every finding names its rule, the measurement and the fix, and the exit code fails a CI build. A clean run ends with0 block.$npx esigncomply check --url http://localhost:3000/signup
Going live
Test and live share nothing, so going live is four moves and no code change.
- 01Register your domainEnter your production host in the dashboard under Domains. Registering
app.example.comcoversexample.comand every subdomain, and every plan, Free included, covers that one domain. - 02Verify it with one TXT recordAdd a TXT record named
_esigncomplywith the valueesc-verify=<token>that the dashboard shows. Esign Comply checks every minute for the first hour. Leave the record in place: it is checked again every day. - 03Add your organization detailsEnter your organization's legal name and country in the dashboard. The Free plan covers 10 live signature events a month with no checkout. Starter is $200 per year for 2,000 live signature events, and Unlimited is $1,200 per year. One event is one signer's completed signing act, so the terms and the privacy notice accepted together at signup count once.
- 04Switch to the live keyCreate a live key (
esc_live_...) and set it asESIGNCOMPLY_API_KEYin the Vercel project's Production environment only. Copy your documents and profile to live from the dashboard and set the live IDs beside it. Preview and Development keep the test key.
In live mode context.url has to be inside your registered domain, browser calls are accepted only from it, and a finding at Block level stops the record from being sealed. Run the conformance check until nothing blocks before you switch keys.
Have your AI tool do it instead
Paste this into Cursor, Claude Code or any coding agent that is open on your repository. It points the tool at this page and at the setup runbook, so it builds the same seven files against your own schema.
The prompt generator writes the long version: your own document and profile IDs, the rule packs for your regions and the stack you pick, in one prompt.
Generate a promptAdd a signup clickwrap to this Next.js App Router and Supabase app with Esign Comply. A new user accepts our Terms of Service and Privacy Notice before the account is created. We render every screen. Esign Comply observes it and keeps the independent record. Read these first and follow them exactly: - https://esigncomply.com/setup.md - https://esigncomply.com/auth.md - https://esigncomply.com/llms.txt - https://esigncomply.com/guides/nextjs-supabase-clickwrap (working code for this stack: use it as the reference) Stack - Packages (the only ones that exist): esigncomply on the server, @esigncomply/browser and @esigncomply/react in client components. - The secret key is in ESIGNCOMPLY_API_KEY. Import it only in files that import "server-only". Build 1. Server action: create the session with esc.sessions.create and an idempotency key. Return only the client token, the API URL and the pinned version IDs. Save the signer ID and version IDs in an acceptances table with row-level security. 2. Client component: attach with useCeremony, report each document link with useDocument, and observe our own unchecked checkbox and our Create account button. Call complete() from the user's real click. 3. Server action: before supabase.auth.admin.createUser, read the record with esc.records.get and require status recorded, timestamped or anchored, the expected livemode, and the saved signer ID and version IDs. Store the record ID and the receipt on the row. Never - Never invent API methods, packages or legal wording. - Never pre-check the box, auto-submit or click for the user. - Never put the secret key in client code, in a template or in the repository, and never print it. - Never create the account before the server has confirmed the record. If anything conflicts with existing code, stop and ask me. Finish with npx esigncomply check --url http://localhost:3000/signup and fix every finding marked "block".
Questions about a clickwrap in Next.js and Supabase
How do I add a clickwrap to a Next.js and Supabase app?
Create the session in a server action with the Node SDK, attach the React hooks to your own checkbox and button in a client component, and confirm the record in a second server action before you call supabase.auth.admin.createUser. Store the record ID and the signed receipt in an acceptances table. The seven files on this page are the whole flow.
Where does the Esign Comply key go in a Next.js app?
In a server environment variable named ESIGNCOMPLY_API_KEY, in .env.local and in your Vercel project. Never give it a NEXT_PUBLIC_ name. Import the client only from files that import server-only, so the build fails if a client component reaches for it. The browser receives a short-lived client token for one session and nothing else.
Read the Node SDK referenceShould I use @esigncomply/browser or @esigncomply/react in Next.js?
Use the React hooks in a React app. useCeremony attaches to the session in an effect, attaches once under strict mode and destroys the ceremony on unmount. useDocument reports each document link. Both sit on top of @esigncomply/browser, so every method of the ceremony object is still there when you need it.
Read the React hooks referenceHow does Supabase row-level security apply to the acceptances table?
Row-level security is enabled with one select policy: a signed-in user can read their own rows. There are no insert, update or delete policies, so the browser cannot write an acceptance. Only your server writes, through the service-role client, after it has confirmed the record with the secret key.
Can I add Google or GitHub sign-in next to the form?
Yes. Put the social sign-in buttons in a separate container with their own notice and their own session. One assent container holds one primary button (rule CR-07), so the Create account button keeps the container on this page to itself.
Read the full Next.js guideShip the Next.js signup today. Leave the record to us.
Free plan: 10 live signatures a month and a full test mode. No card required.