# Add a clickwrap to a Next.js and Supabase app

> Add a clickwrap to a Next.js and Supabase signup. Seven working files: server action, React form, server confirmation, RLS table and signed webhook.

Source: https://esigncomply.com/guides/nextjs-supabase-clickwrap

Stack guide · Next.js and Supabase

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.

[Get started](https://esigncomply.com/signup) · [Read the quickstart](https://esigncomply.com/docs/quickstart)

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

**Server actions**

`app/signup/actions.ts`

```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 };
}
```

**Signup form**

`app/signup/signup-form.tsx`

```tsx
// 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}&apos;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" />; }
```

**Confirm**

`lib/esign-confirm.ts`

```ts
// 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);
}
```

**Migration**

`supabase/migrations/20261122000000_acceptances.sql`

```sql
-- 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.
```

**Document page**

`app/legal/[slug]/page.tsx`

```tsx
// 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>
  );
}
```

**Webhook**

`app/api/esigncomply/webhook/route.ts`

```ts
// 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
}
```

**Server clients**

lib/esigncomply.ts and lib/supabase-admin.ts

```ts
// 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.

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

`app/signup/actions.ts`

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

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

`app/signup/signup-form.tsx`

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

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

`lib/esign-confirm.ts`

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

### The migration: one `acceptances` table with row-level security

`supabase/migrations/20261122000000_acceptances.sql`

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.tsx`

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.ts`

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

### `lib/esigncomply.ts` and `lib/supabase-admin.ts`: two server-only clients

lib/esigncomply.ts and lib/supabase-admin.ts

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. **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. **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. **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. **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. **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. **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. **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`

[Create a free account](https://esigncomply.com/signup) · [What test mode does](https://esigncomply.com/docs/guides/test-mode) · [The conformance rules](https://esigncomply.com/docs/conformance)

Live mode

## Going live

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

[See pricing](https://esigncomply.com/pricing) · [Register a domain](https://esigncomply.com/docs/guides/domains)

1. **Register your domain**

   Enter 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. **Verify it with one TXT record**

   Add 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. **Add your organization details**

   Enter 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. **Switch to the live key**

   Create 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](https://esigncomply.com/product/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](https://esigncomply.com/product/prompt-generator)

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".
```

### Open the page for your AI tool

- [Cursor](https://esigncomply.com/build/cursor)
- [Claude Code](https://esigncomply.com/build/claude-code)
- [Codex](https://esigncomply.com/build/codex)
- [Windsurf](https://esigncomply.com/build/windsurf)
- [GitHub Copilot](https://esigncomply.com/build/github-copilot)
- [Devin](https://esigncomply.com/build/devin)
- [Lovable](https://esigncomply.com/build/lovable)
- [v0](https://esigncomply.com/build/v0)
- [Bolt](https://esigncomply.com/build/bolt)
- [Replit](https://esigncomply.com/build/replit)
- [ChatGPT](https://esigncomply.com/build/chatgpt)
- [Grok](https://esigncomply.com/build/grok)
- [Grokbot](https://esigncomply.com/build/grokbot)
- [Muse](https://esigncomply.com/build/muse)
- [All AI tools](https://esigncomply.com/build#tools)

## 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](https://esigncomply.com/docs/sdk/node)

### 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](https://esigncomply.com/docs/sdk/react)

### 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](https://esigncomply.com/docs/guides/nextjs)

### The same clickwrap in another stack

- [Rails](https://esigncomply.com/guides/rails-clickwrap)
- [Django](https://esigncomply.com/guides/django-clickwrap)
- [Laravel](https://esigncomply.com/guides/laravel-clickwrap)
- [React Native](https://esigncomply.com/guides/react-native-clickwrap)
- [All stack guides](https://esigncomply.com/guides)

[Build your own clickwrap](https://esigncomply.com/build/clickwrap) · [Use cases with live demos](https://esigncomply.com/use-cases) · [Clickwrap and browsewrap compared](https://esigncomply.com/learn/clickwrap-vs-browsewrap)

## Ship the Next.js signup today. Leave the record to us.

[Get started](https://esigncomply.com/signup) · [Documentation](https://esigncomply.com/docs)

Free plan: 10 live signatures a month and a full test mode. No card required.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.
