Skip to content
DocsMenu

Add e-signatures and clickwrap with React

View as Markdown

Open this page inChatGPTClaudeCursor

To add e-signatures and clickwrap with React, install @esigncomply/react and @esigncomply/browser for the page and esigncomply for your server. The hooks attach to your own checkbox and button. A server route creates the session with the secret key and another confirms the record. Esign Comply seals each acceptance as an independent record.

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 React 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/react.md (the steps and the tested code for React)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

React facts
- Packages (the only ones that exist): @esigncomply/react (hooks, React 18 or later) and @esigncomply/browser for the page; esigncomply (Node.js 20.19 or later) for the server.
- React runs in the browser, so the secret key cannot live in the React app. It is in ESIGNCOMPLY_API_KEY on a server. Never give it a VITE_ prefix: Vite puts every VITE_ variable into the bundle.
- React runs effects twice in development under StrictMode. Request the session once per page load, from a promise kept outside the component.
- The form is on screen before the hooks have a session: render the checkbox disabled and enable it when observeAssent has resolved.
- The page and the document pages must share one origin. In development, proxy /api and /legal from Vite to the server.

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: POST /api/ceremony creates the session with esc.sessions.create and an Idempotency-Key, saves the signer ID and the pinned version IDs in server-owned state, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the registered version from esc.documents.versions.getContent inside <article data-esc-document>, unmodified.
5. React: 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. Server: POST /api/signup/confirm reads the record with esc.records.get and requires: 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:5173/signup --callback http://localhost:5173/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.

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 with POST /v1/agent/api-keys: see the agent account API.
  • Nothing else from Esign Comply. Test mode works on localhost with no card and no domain, and the Free plan includes it in full.
  • A React app built with Vite. To start one: npm create vite@latest my-app -- --template react. This page was run on React 19.3.1 and Vite 8.3.8.
  • Node.js 20.19 or later for the server, which the esigncomply package requires.
  • curl and jq for steps 2 and 3.

Step 1. Install

Install the hooks and the browser SDK for the page, and the server package for the routes that hold the secret key:

npm install @esigncomply/react @esigncomply/browser esigncomply

@esigncomply/react is a thin layer of hooks over @esigncomply/browser. It ships no components: you build every element of the form.

Step 2. Set the key

Put the key in .env in the project folder, with a name that does not start with VITE_. Vite puts every variable that starts with VITE_ into the bundle it ships to the browser, and leaves the others out. Only the server in step 4 reads this file.

# .env (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; 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. 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

A React app has no place for a secret, so three routes live on a server: one creates the session, one renders the document pages, one confirms the record. This quickstart uses one file with Node.js and no framework. Any backend you already have can carry the same routes.

// server/index.js
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";
import { EsignComply } from "esigncomply";

// The secret key stays in this process. The SDK reads ESIGNCOMPLY_API_KEY itself.
const esc = new EsignComply();

// The signer. In your app this is the signed-in user, or the account you are about to create.
const signer = {
  external_id: "user_7c1d",
  email: "dana@example.org",
  name: "Dana Whitfield",
  class: "consumer",
  country: "US",
  region: "US-CA",
};

const DOCUMENTS = {
  terms: process.env.ESIGNCOMPLY_TERMS_ID,
  privacy: process.env.ESIGNCOMPLY_PRIVACY_ID,
};
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";

// Signer ID -> the version IDs this server pinned. Use a table in your database in production.
const pinned = new Map();

function json(res, status, body) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(body));
}

async function body(req) {
  let text = "";
  for await (const chunk of req) text += chunk;
  return text ? JSON.parse(text) : {};
}

async function handle(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);

  // The document pages: each one renders a registered version, unmodified.
  if (req.method === "GET" && url.pathname.startsWith("/legal/")) {
    const documentId = DOCUMENTS[url.pathname.slice("/legal/".length)];
    if (!documentId) return json(res, 404, { error: "not_found" });
    const { data, error } = await esc.documents.versions.getContent(documentId, url.searchParams.get("v") ?? "current");
    if (error) return json(res, 404, { error: error.code });
    res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    return res.end(`<!doctype html><meta charset="utf-8"><article data-esc-document="${data.version_id}">${data.html}</article>`);
  }

  // Step 4: create the session with the secret key. The browser gets the client token only.
  if (req.method === "POST" && url.pathname === "/api/ceremony") {
    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" },
        ],
        // The page that runs the ceremony: the origin the browser reports, plus its path.
        context: { url: `${req.headers.origin ?? url.origin}/signup`, locale: "en-US", purpose: "account_signup" },
      },
      { idempotencyKey: `signup-${signer.external_id}-${randomUUID()}` },
    );
    if (error) return json(res, 502, { error: error.code });
    pinned.set(signer.external_id, session.documents.map((d) => d.version_id));
    return json(res, 200, { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });
  }

  // Step 6: confirm the record with the secret key before the account exists.
  if (req.method === "POST" && url.pathname === "/api/signup/confirm") {
    const { recordId } = await body(req);
    const { data: record, error } = await esc.records.get(String(recordId));
    const expected = [...(pinned.get(signer.external_id) ?? [])].sort();
    const confirmed =
      !error &&
      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 json(res, 409, { confirmed: false });
    // Only now create the account, and store record.id and record.receipt with it.
    return json(res, 200, { confirmed: true, recordId: record.id });
  }

  json(res, 404, { error: "not_found" });
}

// A route that throws must not end the process: answer 500, log it and keep serving.
const server = createServer((req, res) => {
  handle(req, res).catch((error) => {
    console.error(`${req.method} ${req.url}: ${error.message}`);
    if (!res.headersSent) json(res, 500, { error: "server_error" });
  });
});

const port = Number(process.env.PORT ?? 3001);
server.listen(port, () => console.log(`API server on http://localhost:${port}`));

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. The pinned Map is the server-owned state the confirmation compares against: replace it with a table in your database before you run more than one process.

In development Vite forwards the three routes, so the page and the document pages share one origin:

// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: {
    // The three server routes live in your backend. In development Vite forwards them,
    // so the page and the document pages share one origin.
    proxy: {
      "/api": "http://localhost:3001",
      "/legal": "http://localhost:3001",
    },
  },
});

Start the server in one terminal:

node --env-file=.env server/index.js
API server on http://localhost:3001

Step 5. Attach the ceremony in the browser

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.

// src/Signup.jsx
import { useEffect, useRef, useState } from "react";
import { useCeremony, useDocument } from "@esigncomply/react";

// One session per page load. StrictMode runs effects twice in development,
// so the request is kept at module level and both runs share it.
let ceremonyRequest;
function requestCeremony() {
  ceremonyRequest ??= fetch("/api/ceremony", { method: "POST" }).then((response) => response.json());
  return ceremonyRequest;
}

// 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 Signup() {
  // { clientToken, apiUrl, documents } from your server. Never the secret key.
  const [session, setSession] = useState(null);
  useEffect(() => {
    let mounted = true;
    requestCeremony().then((value) => mounted && setSession(value));
    return () => {
      mounted = false;
    };
  }, []);

  const { ceremony, canComplete, error } = useCeremony({ clientToken: session?.clientToken, apiUrl: session?.apiUrl });
  const [terms, privacy] = session?.documents ?? [];
  const tos = useDocument(ceremony, { versionId: terms?.version_id, mode: "hyperlink" });
  const notice = useDocument(ceremony, { versionId: privacy?.version_id, mode: "hyperlink" });

  const assentRef = useRef(null);
  const checkboxRef = useRef(null);
  const submitRef = useRef(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 || !tos.presented || !notice.presented) return;
    void ceremony
      .observeAssent({
        region: assentRef.current, // notice, links, checkbox, button
        checkbox: checkboxRef.current,
        submit: submitRef.current,
      })
      .then(() => setReady(true));
  }, [ceremony, tos.presented, notice.presented]);

  async function onSubmit(event) {
    event.preventDefault();
    try {
      const result = await ceremony.complete(); // the signing act, from the signer's own click
      // The result came to the browser. Your server 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.message);
    }
  }

  return (
    <form onSubmit={onSubmit} style={{ font: "16px/1.5 system-ui, sans-serif", maxWidth: 480, margin: "48px auto", padding: "0 20px" }}>
      <h1>Create account</h1>
      <div ref={assentRef}>
        {/* The form is on screen before the hooks have a session, 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={tos.ref} href={`/legal/terms?v=${terms?.version_id ?? ""}`} style={LINK}>Terms of Service</a> and acknowledge the{" "}
          <a ref={notice.ref} href={`/legal/privacy?v=${privacy?.version_id ?? ""}`} 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>
  );
}

Mount the form:

// src/main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Signup } from "./Signup.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <Signup />
  </StrictMode>,
);

Start Vite in a second terminal and open http://localhost:5173/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_fJi0dVGMX5SQt5FX8pNK

Three details matter. The session request sits at module level, so the two effect runs of StrictMode share one session. The checkbox is disabled until the SDK observes it. React puts the form on screen before the hooks have a session, and the component enables the box once observeAssent has resolved: a box ticked before that fails CR-01. In a test with the session request held back, a click on the box 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. POST /api/signup/confirm in server/index.js 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.

The server prints one line for each confirmation:

confirmed rec_fJi0dVGMX5SQt5FX8pNK (recorded)

A record ID that was made up is refused with status 409:

curl -s -X POST http://localhost:5173/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:5173/signup --callback http://localhost:5173/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:5173/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_fche1awTtVbY5DLQyvko  session ses_ptwMyQTqMLwDjFx8f8aP, 5 events
  768x1024   record rec_5MPMWV08aDgf8TcNT8XB  session ses_4yhi2XtbC1jPfAayoouQ, 5 events
  1440x900   record rec_rJJSKXdUqd808anDaRUk  session ses_dE1Rpxnpv0tgFtB18yZu, 5 events

Summary: 0 block, 0 warn, 27 pass.

Each session shows 5 events: client.attached is recorded once, although StrictMode ran the effect twice.

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.

  1. Register your production domain and verify it. See Register a domain.
  2. Add your organization's legal name, country and address under Go live in the dashboard.
  3. 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_KEY on the server and set ESIGNCOMPLY_LIVE=true in production only. From then on the confirm route refuses every test record there.
  • Serve the built React app and the three routes from one origin. The Vite proxy exists only in development.
  • Replace the pinned Map with a table in your database, and store record.id and record.receipt beside 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

  • Two sessions for one page load. A fetch inside useEffect runs twice in development, because StrictMode mounts every component twice. Keep the request in a promise at module level, as requestCeremony does. A session that is never completed makes no record.
  • domain_mismatch when the page loads. The page was opened from a host that is not on the test allowlist, for example your machine's LAN address from vite --host. Test keys work on localhost and 127.0.0.1 at any port. Add other hosts under Domains in the dashboard. See domain_mismatch.
  • missing_api_key from /api/ceremony. The API server was started without --env-file=.env, so the SDK found no key and the route answers 502. See missing_api_key.
  • 429 when the confirm route reads the record. The route needs no retry loop: the esigncomply package waits for the time in Retry-After and tries again, up to twice. In the test, four confirmations sent at once for one record all answered 200, two of them a second later than the others. See rate_limit_exceeded and Retries and timeouts.

Questions about the React quickstart

Can the React app call Esign Comply without a server?

No. Creating a session and confirming a record both use the secret key, and everything in a React bundle can be read by the visitor. The app needs three server routes, which any backend can carry: this quickstart uses one Node.js file.

Why does the session request sit outside the component?

Because React runs effects twice in development under StrictMode. A request made inside useEffect then creates two sessions for one page load. A promise kept at module level is created once, and both runs wait for the same answer.

Does useCeremony attach twice in StrictMode?

No. The hook attaches once for each pair of client token and API URL, and every component that passes the same pair shares the attachment. The conformance check shows it: each session on this page has 5 events, with client.attached recorded once.

Why do the document pages go through the Vite proxy?

So they share the page's origin. For a link on the same origin the browser SDK reads the linked page and compares its text with the registered version. Without the proxy, Vite answers /legal/terms with the app's own HTML and there is no document to compare.

Does the React 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

Run on 2026-11-26 with React 19.3.1, Vite 8.3.8, @esigncomply/react 1.0.1, @esigncomply/browser 1.0.4, esigncomply 1.0.4 and the conformance check from esigncomply 1.0.4 on Node.js 24.22.1, against the API in test mode.

Last updated · API version 2026-11-21