Skip to content

Next.js with Supabase

Build signup acceptance and NDA signing in a Next.js App Router application with Supabase and Vercel, with Esign Comply recording each ceremony.

This guide adds two flows to a Next.js App Router application that uses Supabase for authentication and data and deploys on Vercel: acceptance of the Terms of Service and Privacy Notice at signup (L1, checkbox and button), and signing of a Mutual NDA (L2, email code and typed name). You build every screen. The browser SDK observes the screens you build and reports each step to Esign Comply, which seals the record.

It follows the same structure as a generated prompt. If you would rather have an AI coding tool do the work, generate a prompt and paste it into your tool. If you have not recorded a test signature yet, start with the quickstart.

Before you start

You need:

  • A test key (esc_test_us_...). Test keys work on localhost without a registered domain. See Test mode.
  • Three documents with a published version each: Terms of Service (doc_8Hq2), Privacy Notice (doc_Pv71) and Mutual NDA (doc_Nd55). See the Documents API. The document names must match the titles you print in the notice text, because CR-02 looks for each title.
  • Two profiles: prof_signup_4f1a (method checkbox, assurance level L1, failure mode fail_closed) and prof_nda_9c2e (method typed, assurance level L2). See the Profiles API.
  • A Supabase project with a public.profiles table keyed by auth.users.id.

Files this guide creates:

File Purpose
lib/esigncomply.ts Server-only SDK client
lib/supabase-admin.ts Server-only Supabase service-role client
lib/esign-confirm.ts Server confirmation of a record
supabase/migrations/…_esign.sql Tables, with row-level security
app/legal/[slug]/page.tsx Document pages that render the registered version
app/signup/actions.ts, app/signup/signup-form.tsx Signup ceremony
app/api/esigncomply/webhook/route.ts Webhook handler
app/nda/[id]/actions.ts, app/nda/[id]/nda-signing.tsx NDA signing

Rules for the interface

Esign Comply checks these on its own record. Rule IDs link to the conformance rules. In test mode a failed check is reported and never blocks, so you can read the finding and repair the page.

  1. Create every session on the server with the secret key. Send only client_token to the browser.
  2. Read required_steps from the session and satisfy each one. Do not hard-code steps.
  3. Show the notice text directly above the action button, in the same container, visible without scrolling at 390 x 844 (CR-04).
  4. Notice wording for signup, verbatim, with links: "By checking the box and clicking Create account, you agree to the Terms of Service and acknowledge the Privacy Notice." Use "Create account" only if signup does not create a payment obligation (CR-02, CR-03).
  5. Underline document links and give them a color that differs from the surrounding text by a contrast ratio of at least 3:1, and at least 4.5:1 against the background. Notice text is at least 14px and never lighter than body text (CR-05, CR-06).
  6. Every checkbox starts unchecked. Every typed-name field starts empty (CR-01).
  7. Only one primary button inside the assent container. Give any other button in it type="button". Put social sign-in buttons in a separate container with their own notice and their own session (CR-07).
  8. Serve each document at a stable page on your domain that renders the registered version fetched from Esign Comply, unmodified (CR-08).
  9. Treat the browser result as untrusted. Grant access only after your server has confirmed the record with the secret key. See Server confirmation.
  10. Pass an Idempotency-Key on session creation.
  11. Below the Create account button, inside the same container, show: "{Company} uses Esign Comply to record this event on its behalf. See {Company}'s Privacy Notice for purposes and roles." Nothing may sit between the notice and the button. This line is information, not a request for consent.

Never. Never pre-check a box, auto-submit, or call .click() on the user's behalf. Never treat sign-in, scrolling, or continued use as acceptance. Never use "By continuing" or "By clicking below" wording. Never put the secret key, or any call that uses it, in a client component. Never proxy @esigncomply/browser calls through your own server. Never cache or copy document text into the repository: always render the registered version. Never write to esign_acceptances from the browser. Never show "signed" or "accepted" before the server has confirmed the record. Never write or change the text of the Terms, Privacy Notice, or NDA in code.

1. Install and configure

npm install esigncomply @esigncomply/browser

Add the key and the webhook secret to .env.local, and to the Vercel project's environment variables (test key for Preview and Development, live key for Production). Neither name starts with NEXT_PUBLIC_.

ESIGNCOMPLY_API_KEY=esc_test_us_...
ESIGNCOMPLY_WEBHOOK_SECRET=whsec_...
SUPABASE_SERVICE_ROLE_KEY=...

Create lib/esigncomply.ts. The server-only import makes the build fail if a client component imports it.

import "server-only";
import { EsignComply } from "esigncomply";

export const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!);

Create 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 } },
);

Server SDK calls return { data, error } and do not throw. Check error every time.

2. Database

Keep your own table of acceptances and store the Esign Comply record ID in it. One record can cover several documents, so the table holds one row per record and document.

create table public.esign_acceptances (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references auth.users(id) on delete cascade,
  signer_id uuid not null,
  record_id text not null,
  document_id text not null,
  version_id text not null,
  purpose text not null,
  signed_at timestamptz not null,
  disputed_at timestamptz,
  created_at timestamptz not null default now(),
  unique (record_id, document_id)
);
alter table public.esign_acceptances enable row level security;
create policy "read own" on public.esign_acceptances
  for select using (auth.uid() = user_id);
-- No insert, update, or delete policies. Only the service role writes.

-- Server-owned state: which versions each session pinned, for confirmation.
create table public.esign_ceremonies (
  session_id text primary key,
  signer_id uuid not null,
  purpose text not null,
  version_ids text[] not null,
  created_at timestamptz not null default now()
);
alter table public.esign_ceremonies enable row level security;
-- No policies. Only the service role reads and writes.

-- Webhook deliveries already handled, keyed by webhook-id.
create table public.esign_webhook_events (
  id text primary key,
  type text not null,
  received_at timestamptz not null default now()
);
alter table public.esign_webhook_events enable row level security;

alter table public.profiles add column if not exists signer_id uuid unique;

3. Document pages

Create app/legal/[slug]/page.tsx for terms, privacy and nda. The page renders the HTML that Esign Comply returns for one exact version, inside <article data-esc-document>. Put nothing else inside the article: the browser SDK hashes the article's text and compares it with the version's render_hash.

Resolve current only when a session is created. Links inside a ceremony carry the pinned version ID (?v=dv_3kT9), and the page fetches by that ID. In this Next.js version params and searchParams are Promises.

import { notFound } from "next/navigation";
import { esc } from "@/lib/esigncomply";
import { PrintButton } from "./print-button";

const DOCUMENTS: Record<string, string> = {
  terms: "doc_8Hq2",
  privacy: "doc_Pv71",
  nda: "doc_Nd55",
};

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();

  return (
    <main>
      <p>
        <a data-esc-download href={`/legal/${slug}/download?v=${data.version_id}`}>
          Download
        </a>{" "}
        <PrintButton />
      </p>
      <article
        data-esc-document={data.version_id}
        lang={data.language}
        dangerouslySetInnerHTML={{ __html: data.html }}
      />
    </main>
  );
}

app/legal/[slug]/print-button.tsx:

"use client";

export function PrintButton() {
  return (
    <button type="button" data-esc-print onClick={() => window.print()}>
      Print
    </button>
  );
}

app/legal/[slug]/download/route.ts returns the stored text of the same version as a file:

import { esc } from "@/lib/esigncomply";

const DOCUMENTS: Record<string, string> = { terms: "doc_8Hq2", privacy: "doc_Pv71", nda: "doc_Nd55" };

export async function GET(request: Request, { params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const version = new URL(request.url).searchParams.get("v") ?? "current";
  const documentId = DOCUMENTS[slug];
  if (!documentId) return new Response("Not found", { status: 404 });

  const { data, error } = await esc.documents.versions.getContent(documentId, version);
  if (error || !data?.text) return new Response("Not found", { status: 404 });

  return new Response(data.text, {
    headers: {
      "Content-Type": "text/plain; charset=utf-8",
      "Content-Disposition": `attachment; filename="${slug}-${data.version_id}.txt"`,
    },
  });
}

The HTML returned by the API is already sanitized. Do not transform it, wrap it in extra text, or copy it into the repository. Render the article on the server, as above: for a linked document the browser SDK fetches the page behind the link and reads the article from its HTML without running scripts, so text that only appears after client-side rendering is not seen. It also looks for the data-esc-download and data-esc-print controls on that page.

4. Signup ceremony

Signup server action

app/signup/actions.ts creates the session. The signer ID is generated on the server and kept in an httpOnly cookie that lives as long as the signup.

"use server";

import { cookies, headers } from "next/headers";
import { esc } from "@/lib/esigncomply";
import { supabaseAdmin } from "@/lib/supabase-admin";
import { confirmRecord } from "@/lib/esign-confirm";

export interface StartInput {
  email: string;
  accountType: "consumer" | "business";
  country: string; // from the form, never from IP
  region?: string; // ISO 3166-2, for example "US-CA"; omit when unknown
  locale: string;
  attempt: number; // increases when a session expires or the inputs change
}

export async function startSignupCeremony(input: StartInput) {
  const jar = await cookies();
  let signerId = jar.get("esc_signer")?.value;
  if (!signerId) {
    signerId = crypto.randomUUID();
    jar.set("esc_signer", signerId, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      maxAge: 60 * 60,
      path: "/",
    });
  }

  const h = await headers();
  const origin = h.get("origin") ?? `https://${h.get("host")}`;

  const { data, error } = await esc.sessions.create(
    {
      profile: "prof_signup_4f1a",
      signer: {
        external_id: signerId,
        email: input.email,
        class: input.accountType,
        country: input.country,
        region: input.region,
      },
      documents: [
        { document: "doc_8Hq2", version: "current" },
        { document: "doc_Pv71", version: "current" },
      ],
      context: { url: `${origin}/signup`, locale: input.locale, purpose: "account_signup" },
    },
    { idempotencyKey: `signup-${signerId}-${input.attempt}` },
  );
  if (error) return { ok: false as const, code: error.code, message: error.message };

  // Server-owned state: the versions this session pinned.
  await supabaseAdmin.from("esign_ceremonies").upsert({
    session_id: data.id,
    signer_id: signerId,
    purpose: "account_signup",
    version_ids: data.documents.map((d) => d.version_id),
  });

  return {
    ok: true as const,
    clientToken: data.client_token,
    apiUrl: data.api_url,
    documents: data.documents.map((d) => ({ documentId: d.document_id, versionId: d.version_id, title: d.title })),
    requiredStrings: data.required_strings,
    warnings: data.warnings,
  };
}

Notes:

  • class is consumer or business from the account type field. Take country and region from the form or your own account data. Do not guess them from an IP address. For U.S. signers, region is the state as an ISO code such as US-CA. If the state is unknown, omit it: the profile's on_unknown_region setting decides which packs apply. See Jurisdictions.
  • Do not hard-code which state rules apply. Read applied_jurisdictions, rules_fired and required_strings from the response and render every required string verbatim in the slot it names.
  • A state without a pack returns the warning state_pack_unavailable:<code> and the session runs on Federal rules. Do not tell the user anything about that state's law.
  • A repeat with the same idempotency key and the same body returns the original session. Increase attempt when the session has expired or the signer changed the email, account type or state, so that a new session is created.

Signup form

app/signup/signup-form.tsx attaches the SDK to the elements you rendered. The SDK watches the checkbox and records intent.captured when the signer ticks it. Your code never sets checked.

"use client";

import { useEffect, useRef, useState } from "react";
import { EsignComply, type Ceremony, type EsignComplyError } from "@esigncomply/browser";
import { finishSignup, reconcileSignup, 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.";

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 tosLinkRef = useRef<HTMLAnchorElement>(null);
  const privacyLinkRef = useRef<HTMLAnchorElement>(null);
  const ceremonyRef = useRef<Ceremony | null>(null);
  const attemptRef = useRef(1);
  const activeRef = useRef(false); // a session exists or is being created

  const [started, setStarted] = useState<Started | null>(null);
  const [ready, setReady] = useState(false);
  const [pending, setPending] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const tos = started?.documents.find((d) => d.documentId === "doc_8Hq2");
  const privacy = started?.documents.find((d) => d.documentId === "doc_Pv71");

  // Start the ceremony once the email is entered, not on submit.
  async function start() {
    if (activeRef.current || !formRef.current) return;
    const form = new FormData(formRef.current);
    const email = String(form.get("email") ?? "");
    if (!/^\S+@\S+\.\S+$/.test(email)) return;
    const country = String(form.get("country") ?? "").toUpperCase();
    const state = String(form.get("state") ?? "").toUpperCase();
    const attempt = attemptRef.current;
    activeRef.current = true;
    const res = await startSignupCeremony({
      email,
      accountType: form.get("accountType") === "business" ? "business" : "consumer",
      country,
      region: country === "US" && state ? `US-${state}` : undefined,
      locale: navigator.language,
      attempt,
    });
    if (attempt !== attemptRef.current) return; // the inputs changed while the request was in flight
    if (res.ok) setStarted(res);
    else {
      activeRef.current = false;
      setMessage(res.message);
    }
  }

  // The session is bound to the email, account type and state it was created with.
  // When one of them changes, or the session expires, drop it and start a new one.
  function reset() {
    attemptRef.current += 1;
    activeRef.current = false;
    if (checkboxRef.current) checkboxRef.current.checked = false; // back to the clear state for the new session
    setStarted(null);
    setReady(false);
  }

  useEffect(() => {
    if (!started || !tos || !privacy) return;
    let cancelled = false;
    let ceremony: Ceremony | undefined;
    (async () => {
      try {
        ceremony = await EsignComply.attach({ clientToken: started.clientToken, apiUrl: started.apiUrl });
        if (cancelled) return ceremony.destroy();
        ceremonyRef.current = ceremony;
        ceremony.on("change", ({ remainingSteps }) => {
          setReady(remainingSteps.length === 1 && remainingSteps[0] === "signature.applied");
        });
        ceremony.on("expired", () => {
          reset();
          void start();
        });

        await ceremony.presentDocument({ versionId: tos.versionId, mode: "hyperlink", link: tosLinkRef.current });
        await ceremony.presentDocument({ versionId: privacy.versionId, mode: "hyperlink", link: privacyLinkRef.current });
        await ceremony.observeAssent({
          region: assentRef.current, // contains notice, links, checkbox, button
          checkbox: checkboxRef.current,
          submit: submitRef.current,
        });
      } catch (err) {
        if (!cancelled) setMessage((err as EsignComplyError).message);
      }
    })();
    return () => {
      cancelled = true;
      ceremony?.destroy();
      ceremonyRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [started]);

  function onSignerFieldChange() {
    if (activeRef.current) reset(); // the next blur starts a new session
  }

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const ceremony = ceremonyRef.current;
    if (!ceremony || !ready || !formRef.current) return;
    const form = new FormData(formRef.current);
    setPending(true);
    setMessage(null);
    try {
      const result = await ceremony.complete(); // { recordId, receipt, verifyUrl, status }
      const outcome = await finishSignup(form, result.recordId); // step 5
      if (outcome.ok) window.location.assign("/app");
      else setMessage(outcome.message);
    } catch (err) {
      const error = err as EsignComplyError;
      if (error.code === "client_token_expired") {
        reset();
        void start();
        setMessage("Your session expired. Check the box again to continue.");
      } else if (error.code === "network_error" || error.status >= 500) {
        // Never proceed without a record, and never ask for a second act before reconciling.
        setMessage(INCONCLUSIVE);
        const outcome = await reconcileSignup(form);
        if (outcome.ok) window.location.assign("/app");
      } else {
        setMessage(error.message); // typed error with the rule ID and a fix
      }
    } finally {
      setPending(false);
    }
  }

  return (
    <form ref={formRef} onSubmit={onSubmit} onBlur={() => void start()}>
      <label>
        Email <input name="email" type="email" autoComplete="email" required onChange={onSignerFieldChange} />
      </label>
      <label>
        Password <input name="password" type="password" autoComplete="new-password" required minLength={12} />
      </label>
      <label>
        Account type{" "}
        <select name="accountType" defaultValue="consumer" onChange={onSignerFieldChange}>
          <option value="consumer">Personal</option>
          <option value="business">Business</option>
        </select>
      </label>
      <label>
        Country <input name="country" defaultValue="US" maxLength={2} required onChange={onSignerFieldChange} />
      </label>
      <label>
        State <input name="state" placeholder="CA" maxLength={2} onChange={onSignerFieldChange} />
      </label>

      <div ref={assentRef}>
        <input ref={checkboxRef} id="agree" type="checkbox" />
        <label htmlFor="agree">
          By checking the box and clicking Create account, you agree to the{" "}
          <a ref={tosLinkRef} href={tos ? `/legal/terms?v=${tos.versionId}` : "/legal/terms"} target="_blank" rel="noopener">
            Terms of Service
          </a>{" "}
          and acknowledge the{" "}
          <a ref={privacyLinkRef} href={privacy ? `/legal/privacy?v=${privacy.versionId}` : "/legal/privacy"} target="_blank" rel="noopener">
            Privacy Notice
          </a>
          .
        </label>
        <button ref={submitRef} type="submit" disabled={!ready || pending}>
          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>

      {message ? <p role="alert">{message}</p> : null}
    </form>
  );
}

The button stays disabled until ceremony.remainingSteps() contains only "signature.applied". The change event fires whenever that list changes, including when the signer unticks the box.

The only place this component writes to the checkbox is reset(), which returns it to unchecked when a session is replaced. A new session must find the control in its clear state (CR-01). Nothing ever sets it to checked.

5. Server confirmation

This is the only place access is granted. lib/esign-confirm.ts reads the record with the secret key and compares it with server-owned state. The checks are explained in Server confirmation.

import "server-only";
import { esc } from "@/lib/esigncomply";
import { supabaseAdmin } from "@/lib/supabase-admin";

const SEALED = new Set(["recorded", "timestamped", "anchored"]);

export async function confirmRecord(input: { recordId: string; signerId: string; purpose: string }) {
  const { data: ceremonies } = await supabaseAdmin
    .from("esign_ceremonies")
    .select("session_id, version_ids")
    .eq("signer_id", input.signerId)
    .eq("purpose", input.purpose);

  const { data: record, error } = await esc.records.get(input.recordId);
  if (error) return { ok: false as const, reason: error.code };

  const versions = record.documents.map((d) => d.version_id).sort().join(",");
  const pinned = (ceremonies ?? []).some((c) => [...c.version_ids].sort().join(",") === versions);

  const ok =
    SEALED.has(record.status) &&
    record.signer.external_id === input.signerId &&
    record.livemode === (process.env.VERCEL_ENV === "production") &&
    pinned;

  return ok ? { ok: true as const, record } : { ok: false as const, reason: "record_mismatch" };
}

export async function saveAcceptances(
  record: { id: string; signed_at: string; documents: Array<{ document_id: string; version_id: string }> },
  input: { signerId: string; userId: string | null; purpose: string },
) {
  return supabaseAdmin.from("esign_acceptances").upsert(
    record.documents.map((d) => ({
      user_id: input.userId,
      signer_id: input.signerId,
      record_id: record.id,
      document_id: d.document_id,
      version_id: d.version_id,
      purpose: input.purpose,
      signed_at: record.signed_at,
    })),
    { onConflict: "record_id,document_id" },
  );
}

Add finishSignup and reconcileSignup to app/signup/actions.ts, and extend its import to import { confirmRecord, saveAcceptances } from "@/lib/esign-confirm";:

const INCONCLUSIVE = "We could not confirm whether your acceptance was recorded. Please wait while we check.";

export async function finishSignup(form: FormData, recordId: string) {
  const signerId = (await cookies()).get("esc_signer")?.value;
  if (!signerId) return { ok: false as const, message: "Your signup session has ended. Start again." };

  const confirmed = await confirmRecord({ recordId, signerId, purpose: "account_signup" });
  if (!confirmed.ok) return { ok: false as const, message: INCONCLUSIVE }; // do not create the 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 supabaseAdmin.from("profiles").upsert({ id: created.user.id, signer_id: signerId });
  await saveAcceptances(confirmed.record, { signerId, userId: created.user.id, purpose: "account_signup" });
  return { ok: true as const };
}

// Called when the browser lost the response: look for the record on the existing session.
export async function reconcileSignup(form: FormData) {
  const signerId = (await cookies()).get("esc_signer")?.value;
  if (!signerId) return { ok: false as const, message: INCONCLUSIVE };
  const { data: ceremony } = await supabaseAdmin
    .from("esign_ceremonies")
    .select("session_id")
    .eq("signer_id", signerId)
    .eq("purpose", "account_signup")
    .order("created_at", { ascending: false })
    .limit(1)
    .maybeSingle();
  if (!ceremony) return { ok: false as const, message: INCONCLUSIVE };

  const { data: session, error } = await esc.sessions.get(ceremony.session_id);
  if (error || !session.record_id) return { ok: false as const, message: INCONCLUSIVE };
  return finishSignup(form, session.record_id);
}

Test it: calling finishSignup with a made-up record ID must not create a user.

6. Webhook

app/api/esigncomply/webhook/route.ts covers a browser that closed before step 5 ran. Read the raw body before anything parses it, verify the signature, and handle each delivery once, keyed by webhook-id. Route handlers run on the Node.js runtime by default; keep it that way. Return 200 within 5 seconds. Event types and payloads are listed under Webhooks.

import { esc } from "@/lib/esigncomply";
import { supabaseAdmin } from "@/lib/supabase-admin";
import { confirmRecord, saveAcceptances } from "@/lib/esign-confirm";

export async function POST(request: Request) {
  const rawBody = await request.text();
  const { data: event, error } = await esc.webhooks.verify(
    rawBody,
    request.headers,
    process.env.ESIGNCOMPLY_WEBHOOK_SECRET!,
  );
  if (error) return new Response("Invalid signature", { status: 400 });

  // Deliveries are at-least-once. Handle each webhook-id once.
  const webhookId = request.headers.get("webhook-id")!;
  const { error: seen } = await supabaseAdmin
    .from("esign_webhook_events")
    .insert({ id: webhookId, type: event.type });
  if (seen) return new Response(null, { status: 200 });

  switch (event.type) {
    case "record.completed": {
      const signerId = event.data.signer_external_id;
      const purpose = event.data.purpose ?? "account_signup";
      const confirmed = await confirmRecord({ recordId: event.data.record_id, signerId, purpose });
      if (confirmed.ok) {
        const { data: profile } = await supabaseAdmin
          .from("profiles")
          .select("id")
          .eq("signer_id", signerId)
          .maybeSingle();
        await saveAcceptances(confirmed.record, { signerId, userId: profile?.id ?? null, purpose });
      }
      break;
    }
    case "record.disputed":
      await supabaseAdmin
        .from("esign_acceptances")
        .update({ disputed_at: new Date().toISOString() })
        .eq("record_id", event.data.record_id);
      await notifyAdmin("A signer disputed a record", `Record ${event.data.record_id}`);
      break;
    case "signer.reacceptance_required":
      break; // the gate in step 7 handles it
    case "guidance.notice_published": {
      const { data: notice } = await esc.guidance.notices.get(event.data.notice_id);
      if (notice) await notifyAdmin(notice.title, notice.summary);
      break; // forward only; do not change application behavior
    }
    default:
      break; // ignore event types you do not recognize
  }
  return new Response(null, { status: 200 });
}

async function notifyAdmin(subject: string, text: string) {
  // Send with your own email provider to your admin address.
  console.info(`[esigncomply] ${subject}: ${text}`);
}

To receive test webhooks on localhost, run npx esigncomply webhooks listen. See the CLI.

7. Gate and re-acceptance

When you publish a version with material_change: true, earlier acceptances of that document become outstanding. In the authenticated layout, ask Esign Comply whether the signed-in user has anything outstanding, cache the answer for 5 minutes per user, and redirect to /accept-updates if so. That page runs the same ceremony as signup with purpose: "policy_update", an unchecked checkbox labelled "I agree to the updated [document titles]", and a button labelled "Accept and continue". Offer "Log out" as the alternative. Do not offer "Remind me later".

lib/esign-gate.ts:

import "server-only";
import { esc } from "@/lib/esigncomply";

export interface OutstandingDocument {
  documentId: string;
  name: string;
  summaryOfChanges: string | null;
}

const TTL_MS = 5 * 60_000;
const cache = new Map<string, { at: number; value: OutstandingDocument[] }>();

export async function outstandingDocuments(signerId: string): Promise<OutstandingDocument[]> {
  const hit = cache.get(signerId);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.value;

  const { data, error } = await esc.signers.status(signerId);
  if (error) return hit?.value ?? []; // keep the last known answer; see the Re-acceptance guide

  const value = data.documents
    .filter((d) => d.outstanding)
    .map((d) => ({ documentId: d.document_id, name: d.name, summaryOfChanges: d.summary_of_changes }));
  cache.set(signerId, { at: Date.now(), value });
  return value;
}

export function clearOutstanding(signerId: string) {
  cache.delete(signerId);
}

app/(app)/layout.tsx:

import { redirect } from "next/navigation";
import { getSignedInUser } from "@/lib/auth"; // your Supabase Auth helper
import { outstandingDocuments } from "@/lib/esign-gate";

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const user = await getSignedInUser();
  if (!user) redirect("/login");
  if ((await outstandingDocuments(user.signerId)).length > 0) redirect("/accept-updates");
  return <>{children}</>;
}

Keep /accept-updates outside this layout. The blocking page, its server actions, the response of the status call and the choice of what to do when the check fails are in Re-acceptance.

8. NDA signing

The NDA profile is L2 with a typed name, so the session's required_steps include identity.verified in addition to the document, notice, intent and final act. See L2 verification.

NDA server action

app/nda/[id]/actions.ts:

"use server";

import { headers } from "next/headers";
import { esc } from "@/lib/esigncomply";
import { supabaseAdmin } from "@/lib/supabase-admin";
import { confirmRecord, saveAcceptances } from "@/lib/esign-confirm";
import { getSignedInUser } from "@/lib/auth"; // your Supabase Auth helper

export async function startNdaCeremony(ndaId: string, attempt: number) {
  const user = await getSignedInUser(); // { id, email, name, signerId }
  const h = await headers();
  const origin = h.get("origin") ?? `https://${h.get("host")}`;

  const { data, error } = await esc.sessions.create(
    {
      profile: "prof_nda_9c2e",
      signer: { external_id: user.signerId, email: user.email, name: user.name, class: "business", country: "US" },
      documents: [{ document: "doc_Nd55", version: "current" }],
      context: { url: `${origin}/nda/${ndaId}`, locale: "en-US", purpose: "nda" },
      metadata: { nda_id: ndaId },
    },
    { idempotencyKey: `nda-${ndaId}-${user.signerId}-${attempt}` },
  );
  if (error) return { ok: false as const, message: error.message };

  const pinned = data.documents[0];
  await supabaseAdmin.from("esign_ceremonies").upsert({
    session_id: data.id,
    signer_id: user.signerId,
    purpose: "nda",
    version_ids: [pinned.version_id],
  });

  // The exact pinned version, to render inline.
  const content = await esc.documents.versions.getContent("doc_Nd55", pinned.version_id);
  if (content.error) return { ok: false as const, message: content.error.message };

  return {
    ok: true as const,
    clientToken: data.client_token,
    apiUrl: data.api_url,
    versionId: pinned.version_id,
    html: content.data.html as string,
    signerName: user.name,
  };
}

export async function finishNda(recordId: string) {
  const user = await getSignedInUser();
  const confirmed = await confirmRecord({ recordId, signerId: user.signerId, purpose: "nda" });
  if (!confirmed.ok) {
    return { ok: false as const, message: "We could not confirm whether your signature was recorded. Please wait while we check." };
  }
  await saveAcceptances(confirmed.record, { signerId: user.signerId, userId: user.id, purpose: "nda" });
  return { ok: true as const };
}

NDA signing component

app/nda/[id]/nda-signing.tsx. Page layout, top to bottom: the full pinned NDA inline with download and print; email verification; then the assent container with the review line, the notice, the name field and the button. "Decline" sits outside the container. The review line is inside the assent container so that the captured notice text names the document (CR-02).

"use client";

import { useEffect, useRef, useState } from "react";
import { EsignComply, type Ceremony, type EsignComplyError } from "@esigncomply/browser";
import { finishNda, startNdaCeremony } from "./actions";

type Started = Extract<Awaited<ReturnType<typeof startNdaCeremony>>, { ok: true }>;

export function NdaSigning({ ndaId, company }: { ndaId: string; company: string }) {
  const articleRef = useRef<HTMLElement>(null);
  const reviewRef = useRef<HTMLParagraphElement>(null);
  const assentRef = useRef<HTMLDivElement>(null);
  const nameRef = useRef<HTMLInputElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const ceremonyRef = useRef<Ceremony | null>(null);

  const [started, setStarted] = useState<Started | null>(null);
  const [destination, setDestination] = useState<string | null>(null);
  const [verified, setVerified] = useState(false);
  const [canSend, setCanSend] = useState(true);
  const [ready, setReady] = useState(false);
  const [done, setDone] = useState<{ verifyUrl: string | null } | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const requestedRef = useRef(false);

  useEffect(() => {
    if (requestedRef.current) return; // one session per page load
    requestedRef.current = true;
    startNdaCeremony(ndaId, 1).then((res) => (res.ok ? setStarted(res) : setMessage(res.message)));
  }, [ndaId]);

  useEffect(() => {
    if (!started) return;
    let cancelled = false;
    let ceremony: Ceremony | undefined;
    (async () => {
      try {
        ceremony = await EsignComply.attach({ clientToken: started.clientToken, apiUrl: started.apiUrl });
        if (cancelled) return ceremony.destroy();
        ceremonyRef.current = ceremony;
        ceremony.on("change", ({ remainingSteps }) => {
          setReady(remainingSteps.length === 1 && remainingSteps[0] === "signature.applied");
        });
        await ceremony.presentDocument({ versionId: started.versionId, mode: "inline", container: articleRef.current });
        await ceremony.reviewPresented({ container: reviewRef.current });
        await ceremony.observeAssent({ region: assentRef.current, typedName: nameRef.current, submit: submitRef.current });
      } catch (err) {
        if (!cancelled) setMessage((err as EsignComplyError).message);
      }
    })();
    return () => {
      cancelled = true;
      ceremony?.destroy();
      ceremonyRef.current = null;
    };
  }, [started]);

  async function sendCode() {
    try {
      const v = await ceremonyRef.current!.verify.start({ method: "email_otp" });
      setDestination(v.destination); // masked, for example d***@example.org
      setCanSend(false);
      setTimeout(() => setCanSend(true), 30_000); // allow resend after 30 seconds
    } catch (err) {
      setMessage((err as EsignComplyError).message);
    }
  }

  async function confirmCode(form: FormData) {
    try {
      const result = await ceremonyRef.current!.verify.confirm({ code: String(form.get("code")) });
      if (result.status === "confirmed") setVerified(true);
      else setMessage(`That code did not match. Attempts left: ${result.attemptsRemaining}.`);
    } catch (err) {
      setMessage((err as EsignComplyError).message); // lockout ends the session
    }
  }

  async function sign(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    try {
      const result = await ceremonyRef.current!.complete();
      const outcome = await finishNda(result.recordId);
      if (outcome.ok) setDone({ verifyUrl: result.verifyUrl });
      else setMessage(outcome.message);
    } catch (err) {
      setMessage((err as EsignComplyError).message);
    }
  }

  if (!started) return <p>{message ?? "Loading the agreement."}</p>;
  if (done) {
    return (
      <p>
        Signed. A copy has been emailed to you by Esign Comply.{" "}
        {done.verifyUrl ? <a href={done.verifyUrl}>Verify this record</a> : null}{" "}
        <a href={`/legal/nda/download?v=${started.versionId}`}>Download copy</a>
      </p>
    );
  }

  return (
    <main>
      <p>
        <a data-esc-download href={`/legal/nda/download?v=${started.versionId}`}>Download</a>{" "}
        <button type="button" data-esc-print onClick={() => window.print()}>Print</button>
      </p>
      <article ref={articleRef} data-esc-document={started.versionId} dangerouslySetInnerHTML={{ __html: started.html }} />

      <section aria-label="Verify your email">
        {verified ? (
          <p>Email verified.</p>
        ) : (
          <>
            <button type="button" onClick={sendCode} disabled={!canSend}>
              {destination ? "Send a new code" : "Send code"}
            </button>
            {destination ? (
              <form action={confirmCode}>
                <label>
                  Enter the 6-digit code sent to {destination}
                  <input name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9]{6}" required />
                </label>
                <button type="submit">Verify</button>
              </form>
            ) : null}
          </>
        )}
      </section>

      <form onSubmit={sign}>
        <div ref={assentRef}>
          <p ref={reviewRef}>
            You are signing the Mutual NDA between {company} and {started.signerName} as {started.signerName}.
          </p>
          <p>
            By typing your name and clicking Sign NDA, you agree to sign this agreement electronically and to be bound by it.
          </p>
          <label htmlFor="legal-name">Type your full legal name</label>
          <input ref={nameRef} id="legal-name" name="legalName" type="text" autoComplete="off" />
          <button ref={submitRef} type="submit" disabled={!ready}>
            Sign NDA
          </button>
        </div>
      </form>
      <button type="button" onClick={() => ceremonyRef.current?.cancel()}>
        Decline
      </button>

      {message ? <p role="alert">{message}</p> : null}
    </main>
  );
}

The name field starts empty and is never prefilled from the account. The SDK reads the name once, at the signing act, and does not send keystrokes. Do not render a signature image or a cursive font as the signature.

9. Language

Disclose the languages you offer before contracting. The session locale is a default. Render the version the signer selects or reasonably understands, and record a choice that differs from the locale:

await ceremony.languageSelected("de");

If a mandatory local language is not available, do not start the ceremony.

10. Errors

Browser SDK methods reject with a typed EsignComplyError that carries code, rule, fix and docUrl. Server SDK calls return { data, error }.

Situation What to do
ceremony.complete() rejected with a rule ID (conformance_failed, steps_incomplete) Show the message, keep the form, do not retry automatically.
Network failure or a 5xx Show "We could not confirm whether your acceptance was recorded. Please wait while we check." Reconcile the same session before asking for another act. Never proceed without a record.
client_token_expired Create a new session with a new idempotency key and attach again.
session_not_active The session is completed or cancelled. Read its record_id on the server, or create a new session.
verification_failed Wrong or expired code. After 5 wrong attempts the session ends: create a new one.

Verify before you report success

  1. npm run build passes, and no file under app/** marked "use client" imports esigncomply or reads ESIGNCOMPLY_API_KEY.
  2. Run npx esigncomply check --url http://localhost:3000/signup and npx esigncomply check --url http://localhost:3000/nda/test. Fix every finding marked block. List every finding marked warn.
  3. Confirm by test that submitting with the box unchecked does nothing, and that calling finishSignup with a made-up record ID does not create a user.
  4. Open the test record in the dashboard: it shows what was observed, what was asserted, and the conformance findings. Findings describe measurable design facts. They are not a statement that a flow is lawful or enforceable.

Your obligations and recommendations

A generated prompt also lists duties that the selected rule packs identify for your company, and practices Esign Comply recommends. Esign Comply lists them and does not perform, monitor, or verify them. Examples for this flow: letting EU and UK consumers correct input errors before an order, keeping your own copy of records for any period another law requires, and notifying users in advance of a material terms update. Read them for your profile with the Guidance API, and see Supplements for the optional reports you can file about them.