Add e-signatures and clickwrap with Next.js
To add e-signatures and clickwrap with Next.js, install esigncomply, @esigncomply/react and @esigncomply/browser. A Server Component creates the session with the secret key, a client component attaches the hooks to your own checkbox and button, and a Route Handler confirms the record. Esign Comply seals each acceptance as an independent record you can verify.
Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.
Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:
Add Esign Comply clickwrap to my Next.js app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.
Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/nextjs.md (the steps and the tested code for Next.js)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)
Next.js facts
- Packages (the only ones that exist): esigncomply (server), @esigncomply/react (hooks) and @esigncomply/browser. Use the App Router.
- The secret key is in ESIGNCOMPLY_API_KEY in .env.local. Never give it a NEXT_PUBLIC_ name. Create the client in lib/esigncomply.ts with import "server-only", and never import that file from a "use client" file.
- Server SDK calls return { data, error } and do not throw. Check error every time.
- Module state is not shared between a page and a Route Handler in development. Keep the pinned version IDs in your database. Only for a first local run, a Map on globalThis works.
- A Server Component cannot set cookies. If the pinned state goes into a cookie, create the session in a Route Handler or a Server Action.
- The form is in the server HTML before the page hydrates: render the checkbox disabled and enable it when observeAssent has resolved.
Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server Component app/signup/page.tsx: create the session with esc.sessions.create and an Idempotency-Key, save the signer ID and the pinned version IDs in server-owned state, and pass only clientToken, apiUrl and the version IDs to the client component.
4. Server Component app/legal/[slug]/page.tsx: render the registered version from esc.documents.versions.getContent inside <article data-esc-document>, unmodified.
5. Client component: useCeremony({ clientToken, apiUrl }), useDocument for each link, ceremony.observeAssent({ region, checkbox, submit }) from an effect, then ceremony.complete() in the submit handler. The checkbox is uncontrolled and starts unchecked.
6. Route Handler app/api/signup/confirm/route.ts: read the record with esc.records.get and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the server-owned state. Only then create the account.
Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.
Check before you report success
- Run: npx esigncomply check --url http://localhost:3000/signup --callback http://localhost:3000/api/signup/confirm
Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.
Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
The rest of this page is the same integration by hand, in eight steps. The full application, with a Supabase table, the webhook and the re-acceptance gate, is in the Next.js guide.
Before you start
- A test API key. Create an account with your email, no card, then choose Create test key in the dashboard. The key is shown once and starts with
esc_test_. An AI agent with an agent token creates it withPOST /v1/agent/api-keys: see the agent account API. - Nothing else from Esign Comply. Test mode works on
localhostwith no card and no domain, and the Free plan includes it in full. - A Next.js app on the App Router. To start one:
npx create-next-app@latest. This page was run on Next.js 16.4.6 and React 19.3.1. - Node.js 20.19 or later, which the
esigncomplypackage requires. curlandjqfor steps 2 and 3.
Step 1. Install
Install the server package, the hooks, the browser SDK, and server-only, which keeps the server module out of client code:
npm install esigncomply @esigncomply/react @esigncomply/browser server-only
Step 2. Set the key
Put the key in .env.local. Next.js loads this file itself and keeps every variable without a NEXT_PUBLIC_ prefix on the server, so never give the key that prefix.
# .env.local (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:
set -a; . ./.env.local; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
-H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
{
"plan_name": "Free",
"test_events": {
"used_this_month": 0,
"quota_per_month": 500
}
}
A 401 means the key is wrong or revoked: see invalid_api_key. The rules for handling keys are in /auth.md.
Step 3. Register a document version
Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs curl and jq.
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"
# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
-d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
-d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
| jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
-d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
-d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
| jq -r .id; sleep 1
# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
-d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)
printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
It prints the two version IDs, then three lines with your own IDs:
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
Add the three lines to .env.local. The pauses keep the script under the Free plan's 2 requests per second. Keep the names Terms of Service and Privacy Notice: the notice on your page names each document by its registered name, and rule CR-02 checks that it does. With your own documents, publish the text you already have and change the notice to match. See Documents and Profiles.
Step 4. Create a session on the server
One server-only module holds the client, the test signer and the state the confirmation compares against:
// 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!);
// The signer. In your app this is the signed-in user, or the account you are about to create.
export const signer = {
external_id: "user_7c1d",
email: "dana@example.org",
name: "Dana Whitfield",
class: "consumer",
country: "US",
region: "US-CA",
} as const;
export const DOCUMENTS: Record<string, string | undefined> = {
terms: process.env.ESIGNCOMPLY_TERMS_ID,
privacy: process.env.ESIGNCOMPLY_PRIVACY_ID,
};
// Signer ID -> the version IDs this server pinned. It hangs on globalThis so the page and the
// route handler read the same Map. Use a table in your database in production: on a serverless
// host two requests do not share memory.
const store = globalThis as typeof globalThis & { pinned?: Map<string, string[]> };
export const pinned = (store.pinned ??= new Map<string, string[]>());
The Map hangs on globalThis for a reason that is specific to Next.js: in development, module state set while a page renders is not visible to a Route Handler. A plain module-level Map was empty in the confirm route when this page was tested. A table in your database has no such problem, and it is what production needs.
The signup page is a Server Component. It creates the session while it renders and passes three values to the form: the client token, the API URL and the pinned version IDs.
// app/signup/page.tsx
import { randomUUID } from "node:crypto";
import { headers } from "next/headers";
import { DOCUMENTS, esc, pinned, signer } from "@/lib/esigncomply";
import { SignupForm } from "./signup-form";
// A Server Component: the session is created while the page renders, with the secret key.
export default async function SignupPage() {
const h = await headers(); // reading the request also makes this page render per request
const origin = `${h.get("x-forwarded-proto") ?? "http"}://${h.get("host")}`;
const { data: session, error } = await esc.sessions.create(
{
profile: process.env.ESIGNCOMPLY_PROFILE_ID!,
signer,
documents: [
{ document: DOCUMENTS.terms!, version: "current" },
{ document: DOCUMENTS.privacy!, version: "current" },
],
context: { url: `${origin}/signup`, locale: "en-US", purpose: "account_signup" },
},
{ idempotencyKey: `signup-${signer.external_id}-${randomUUID()}` },
);
if (error) return <p role="alert">We could not start the signup. Reload the page to try again.</p>;
const versionIds = session.documents.map((d) => d.version_id);
pinned.set(signer.external_id, versionIds);
// Only the client token, the API URL and the version IDs cross to the browser.
return <SignupForm clientToken={session.client_token} apiUrl={session.api_url} versionIds={versionIds} />;
}
The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.
Step 5. Attach the ceremony in the browser
The form is a client component. The hooks render nothing: useCeremony attaches to the session, useDocument reports each document link, and observeAssent watches the checkbox, the notice and the button you built. Each step goes from the signer's browser straight to Esign Comply.
// app/signup/signup-form.tsx
"use client";
import { useEffect, useRef, useState, type FormEvent } from "react";
import { useCeremony, useDocument } from "@esigncomply/react";
// Document links are underlined and differ from the text around them by at least 3 to 1 (rule CR-05).
const LINK = { color: "#0b57d0", textDecoration: "underline" };
export function SignupForm({ clientToken, apiUrl, versionIds }: { clientToken: string; apiUrl: string; versionIds: string[] }) {
const { ceremony, canComplete, error } = useCeremony({ clientToken, apiUrl });
const [termsId, privacyId] = versionIds;
const terms = useDocument<HTMLAnchorElement>(ceremony, { versionId: termsId, mode: "hyperlink" });
const privacy = useDocument<HTMLAnchorElement>(ceremony, { versionId: privacyId, mode: "hyperlink" });
const assentRef = useRef<HTMLDivElement>(null);
const checkboxRef = useRef<HTMLInputElement>(null);
const submitRef = useRef<HTMLButtonElement>(null);
const [ready, setReady] = useState(false); // true once the SDK observes the checkbox
const [message, setMessage] = useState("");
// Observe the assent controls once both documents are presented.
useEffect(() => {
if (!ceremony || !terms.presented || !privacy.presented) return;
void ceremony
.observeAssent({
region: assentRef.current, // notice, links, checkbox, button
checkbox: checkboxRef.current,
submit: submitRef.current,
})
.then(() => setReady(true));
}, [ceremony, terms.presented, privacy.presented]);
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!ceremony) return;
try {
const result = await ceremony.complete(); // the signing act, from the signer's own click
// The result came to the browser. The route handler confirms the record before anything is granted.
const confirmed = await fetch("/api/signup/confirm", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ recordId: result.recordId }),
});
setMessage(
confirmed.ok
? `Account created. Record ${result.recordId}`
: "We could not confirm whether your acceptance was recorded. Please wait while we check.",
);
} catch (err) {
setMessage(err instanceof Error ? err.message : "Something went wrong.");
}
}
return (
<form onSubmit={onSubmit}>
<h1>Create account</h1>
<div ref={assentRef}>
{/* The form is in the server HTML, so the box stays disabled until the SDK watches it. Only the user changes it. */}
<label>
<input ref={checkboxRef} type="checkbox" disabled={!ready} /> I agree to the Terms of Service and Privacy Notice
</label>
<p>
By checking the box and clicking Create account, you agree to the{" "}
<a ref={terms.ref} href={`/legal/terms?v=${termsId}`} style={LINK}>Terms of Service</a> and acknowledge the{" "}
<a ref={privacy.ref} href={`/legal/privacy?v=${privacyId}`} style={LINK}>Privacy Notice</a>.
</p>
<button ref={submitRef} type="submit" disabled={!canComplete}>
Create account
</button>
</div>
<p role="alert">{message || error?.message}</p>
</form>
);
}
Each link opens a document page on your own domain that renders the registered version, unmodified:
// app/legal/[slug]/page.tsx
import { notFound } from "next/navigation";
import { DOCUMENTS, esc } from "@/lib/esigncomply";
// /legal/terms?v=dv_... renders 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();
return <article data-esc-document={data.version_id} dangerouslySetInnerHTML={{ __html: data.html }} />;
}
Start the app and open http://localhost:3000/signup:
npm run dev
The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows:
Account created. Record rec_xKvqtsUKpNVB0Q4Wt2aj
The checkbox is disabled until the SDK observes it. Next.js sends the form as HTML before the script loads, and React keeps the same elements when it hydrates: a box ticked that early stays ticked and fails CR-01. In a test with the page's scripts held back, the box was disabled in the server HTML and a click on it did nothing. The box is uncontrolled and has no defaultChecked: only the user changes it. The links carry a color that differs from the text around them by at least 3 to 1, which the browser's default link blue on black text does not.
Step 6. Confirm the record on the server
The result of ceremony.complete() was delivered to the browser, so your server does not trust it. A Route Handler reads the record with the secret key and grants access only when four things hold: the status is recorded, timestamped or anchored; livemode is what this deployment expects; the signer is the one this server created the session for; and the document versions are exactly the ones it pinned. This step is never optional.
// app/api/signup/confirm/route.ts
import { esc, pinned, signer } from "@/lib/esigncomply";
const SEALED = ["recorded", "timestamped", "anchored"];
// Test records in development, live records where ESIGNCOMPLY_LIVE is "true": production only.
const LIVE = process.env.ESIGNCOMPLY_LIVE === "true";
export async function POST(request: Request) {
const { recordId } = await request.json();
const { data: record, error } = await esc.records.get(String(recordId));
if (error) return Response.json({ confirmed: false }, { status: 409 });
const expected = [...(pinned.get(signer.external_id) ?? [])].sort();
const confirmed =
SEALED.includes(record.status) &&
record.livemode === LIVE &&
record.signer.external_id === signer.external_id &&
JSON.stringify(record.documents.map((d) => d.version_id).sort()) === JSON.stringify(expected);
console.log(confirmed ? `confirmed ${record.id} (${record.status})` : "refused");
if (!confirmed) return Response.json({ confirmed: false }, { status: 409 });
// Only now create the account, and store record.id and record.receipt with it.
return Response.json({ confirmed: true, recordId: record.id });
}
The dev server prints one line for each confirmation:
confirmed rec_xKvqtsUKpNVB0Q4Wt2aj (recorded)
A record ID that was made up is refused with status 409:
curl -s -X POST http://localhost:3000/api/signup/confirm \
-H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
{"confirmed":false}
See Server confirmation for the webhook that backs this route up when the browser closes early.
Step 7. Check the result
Open the dashboard and choose Records. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.
Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route.
npm install --save-dev playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:3000/signup --callback http://localhost:3000/api/signup/confirm
The report for this page's code, shortened:
Violations that must be refused
REFUSED Submit with the checkbox untouched No record was made.
REFUSED Completion from another origin The API answered 403 domain_mismatch.
REFUSED Programmatic click No record was made.
REFUSED Forged success posted to your callback http://localhost:3000/api/signup/confirm answered 409.
Ceremonies
390x844 record rec_2Z0qcUrpdXRmb5BY0Y6B session ses_sEcRn15ia9Y9Dw2nY4Tp, 5 events
768x1024 record rec_p0kdApqhPGAyKi2qoRNo session ses_tYjvirjkJPDrpWRtQKn6, 5 events
1440x900 record rec_MLubQgWuG1L71cmS6thy session ses_mb7Lw24gHDcHnoMFFiBd, 5 events
Summary: 0 block, 0 warn, 27 pass.
Fix every finding marked block and read every finding marked warn. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on Conformance rules, and every flag of the command is on the CLI page.
Step 8. Go live
Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.
- Register your production domain and verify it. See Register a domain.
- Add your organization's legal name, country and address under Go live in the dashboard.
- Create a live key. It is shown once and starts with
esc_live_.
Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.
Then switch the app over:
- Set the live key as
ESIGNCOMPLY_API_KEYand setESIGNCOMPLY_LIVE=truein production only. From then on the confirm route refuses every test record there. On Vercel, useVERCEL_ENVinstead: see the Vercel quickstart. - Replace the Map with a table in your database. On a serverless host two requests do not share memory at all, so the Map cannot work there. The Next.js guide has the table.
- Store
record.idandrecord.receiptbeside the user.
In live mode context.url must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.
Troubleshooting
- The confirm route answers
409for a real record. The pinned version IDs are missing where the Route Handler looks for them. In development a plain module-level Map set by the page is empty in the route: keep it onglobalThis, aslib/esigncomply.tsdoes, or in your database. A record ID that does not exist fails the same way, withnot_found. - "Cookies can only be modified in a Server Action or Route Handler". The signup page is a Server Component, and a Server Component cannot set a cookie. If you keep the pinned state in a cookie, create the session in a Route Handler or a Server Action, as the Vercel quickstart does.
domain_mismatchwhen the page loads. The page was opened from a host that is not on the test allowlist, for example a preview deployment. Test keys work onlocalhostand127.0.0.1at any port. Add other hosts under Domains in the dashboard. Seedomain_mismatch.429when the confirm route reads the record. The Route Handler needs no retry loop: theesigncomplypackage waits for the time inRetry-Afterand tries again, up to twice. In the test, four confirmations sent at once for one record all answered200, two of them a second later than the others. Seerate_limit_exceededand Retries and timeouts.
Questions about the Next.js quickstart
Does the quickstart use the App Router or the Pages Router?
The App Router. The session is created in a Server Component, the form is a client component, and the confirmation is a Route Handler. It was run on Next.js 16.4.6 with React 19.3.1.
Why is the session created in a Server Component?
Because the page then arrives with the client token already in the form's props, and the hooks attach as soon as it hydrates, with no request of their own for a session. The Server Component runs only on the server, so the secret key and the session call never reach the bundle.
Why does the Map sit on globalThis?
In development, Next.js does not share module state between a page and a Route Handler. When this quickstart was tested, a plain module-level Map set by the page was empty in the confirm route, and the same Map on globalThis held the entry.
Can a Server Action confirm the record instead of a Route Handler?
Yes. A Server Action runs on the server with the same access to the secret key, and the React hooks page shows the form calling one. This quickstart uses a Route Handler so the conformance check can post a forged record ID to it.
Does the Next.js quickstart need a domain or a card?
No. Test mode works on localhost with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.
Next steps
- E-signatures and clickwrap for Next.js: what the integration gives you on this stack, with the things to watch for.
- Next.js guide: the full application with a Supabase table, the webhook and the re-acceptance gate.
- Clickwrap in Next.js and Supabase: the same build as working code, file by file.
- Add e-signatures and clickwrap on Vercel: environment variables, preview deployments and state on Vercel Functions.
- All quickstarts.
Run on 2026-11-26 with Next.js 16.4.6 (App Router, Turbopack), React 19.3.1, esigncomply 1.0.4, @esigncomply/react 1.0.1, @esigncomply/browser 1.0.4 and the conformance check from esigncomply 1.0.4 (--timeout 60), against the API in test mode.
Last updated · API version 2026-11-21