Skip to content
Stack guide · Next.js and Supabase

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.

7 files · copy and run

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/react.

app/signup/actions.ts
// 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 };
}

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.

01

actions.ts: start the ceremony, then finish the signup

app/signup/actions.tsView the file

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.

02

signup-form.tsx: your notice, your checkbox, your button

app/signup/signup-form.tsxView the file

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.

03

esign-confirm.ts: the one place access is granted

lib/esign-confirm.tsView the file

confirmRecord reads the record with the secret key (GET /v1/records/{id}) 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.

04

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.

05

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.

06

The webhook route: the backstop when the tab closes

app/api/esigncomply/webhook/route.tsView the file

record.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://localhost:3000/api/esigncomply/webhook.

07

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.

Test mode

Run it

From an empty account to a sealed test record on localhost. No domain, no card and no deploy.

  1. 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 on localhost on any port with no domain.

  2. 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 checkbox and level L1. The names matter: the notice in the form names each document by its title, and rule CR-02 looks for both. Copy the three IDs.

  3. 03

    Set the environment variables

    Add these to .env.local, and to the Vercel project for Preview and Development. None of the names starts with NEXT_PUBLIC_.

    .env.local
    ESIGNCOMPLY_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=...
  4. 04

    Apply the migration and start the app

    supabase db push applies the migration to your linked Supabase project. Then start the dev server.

    $supabase db push && npm run dev
  5. 05

    Sign up once

    Open http://localhost:3000/signup. Enter an email and move to the next field: the checkbox unlocks when the session is attached. Tick it and click Create account.

  6. 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 acceptances row holds the same record ID and its signed receipt.

  7. 07

    Run the conformance check

    The command reads ESIGNCOMPLY_API_KEY from 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 with 0 block.

    $npx esigncomply check --url http://localhost:3000/signup
Live mode

Going live

Test and live share nothing, so going live is four moves and no code change.

  1. 01
    Register your domainEnter your production host in the dashboard under Domains. Registering app.example.com covers example.com and every subdomain, and every plan, Free included, covers that one domain.
  2. 02
    Verify it with one TXT recordAdd a TXT record named _esigncomply with the value esc-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.
  3. 03
    Add 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.
  4. 04
    Switch to the live keyCreate a live key (esc_live_...) and set it as ESIGNCOMPLY_API_KEY in 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.

Copy-paste prompt

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 prompt
Prompt: clickwrap in Next.js and Supabase
Add 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 reference

Should 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 reference

How 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 guide

Ship 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.

Working with an AI tool? This page is also available as Markdown: /guides/nextjs-supabase-clickwrap.md