Add e-signatures and clickwrap with Fastify
To add e-signatures and clickwrap with Fastify, install fastify, @fastify/static and esigncomply. One route creates the session with the secret key, the browser SDK attaches to your own checkbox and button, and a second route with a JSON schema confirms the record before your app grants anything. 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 Fastify 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/fastify.md (the steps and the tested code for Fastify)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)
Fastify facts
- Packages (the only ones that exist): esigncomply (server, Node.js 20.19 or later, an ES module) and @esigncomply/browser. Without a bundler, load the browser SDK from https://esigncomply.com/sdk/v1/esigncomply.js.
- The secret key is in ESIGNCOMPLY_API_KEY, in a .env file loaded with: node --env-file=.env server.js. Never print it.
- Server SDK calls return { data, error } and do not throw. Check error every time.
- Fastify parses JSON bodies itself. Put a JSON schema on the confirm route so a body without recordId is refused before the handler runs. A request with Content-Type application/json and an empty body is answered 400 by Fastify: the page must send no content type when it sends no body.
- Fastify listens on 127.0.0.1 unless listen() gets a host.
- The page is on screen before the script has a session: 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: app.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: app.get("/legal/:slug") renders the registered version from esc.documents.versions.getContent inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: app.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: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.
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. - Node.js 20.19 or later, which the
esigncomplypackage requires. This page was run on Node.js 24.22.1 with Fastify 5.12.8. curlandjqfor steps 2 and 3.
Step 1. Install
Install Fastify, its static file plugin and the server package in a new folder. The page loads the browser SDK from a script tag, so there is nothing to bundle.
mkdir esigncomply-quickstart && cd esigncomply-quickstart
npm init -y && npm pkg set type=module
npm install fastify @fastify/static esigncomply
mkdir public
Step 2. Set the key
Put the key in .env in the project folder. Node.js does not read this file on its own: the --env-file flag in step 4 loads it. The key stays in the server process and never reaches the page.
# .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
server.js is the whole app: the signup page, the two document pages, the route that creates the session, and the route that confirms the record. app.post("/api/ceremony") creates the session with the secret key and returns three values to the browser: the client token, the API URL and the pinned documents.
// server.js
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import Fastify from "fastify";
import fastifyStatic from "@fastify/static";
import { EsignComply } from "esigncomply";
const app = Fastify({ logger: false });
// 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 request.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();
// The signup page.
app.register(fastifyStatic, { root: join(import.meta.dirname, "public") });
app.get("/signup", (request, reply) => reply.sendFile("signup.html"));
// The document pages: each one renders a registered version, unmodified.
app.get("/legal/:slug", async (request, reply) => {
const documentId = DOCUMENTS[request.params.slug];
if (!documentId) return reply.code(404).send({ error: "not_found" });
const { data, error } = await esc.documents.versions.getContent(documentId, request.query.v ?? "current");
if (error) return reply.code(404).send({ error: error.code });
return reply.type("text/html; charset=utf-8").send(`<!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.
app.post("/api/ceremony", async (request, reply) => {
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: `${request.headers.origin ?? `${request.protocol}://${request.host}`}/signup`, locale: "en-US", purpose: "account_signup" },
},
{ idempotencyKey: `signup-${signer.external_id}-${randomUUID()}` },
);
if (error) return reply.code(502).send({ error: error.code });
pinned.set(signer.external_id, session.documents.map((d) => d.version_id));
return { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents };
});
// Step 6: confirm the record with the secret key before the account exists.
// Fastify parses the JSON body itself, and the schema refuses a body without a record ID.
const confirmBody = { type: "object", required: ["recordId"], properties: { recordId: { type: "string" } } };
app.post("/api/signup/confirm", { schema: { body: confirmBody } }, async (request, reply) => {
const { data: record, error } = await esc.records.get(request.body.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 reply.code(409).send({ confirmed: false });
// Only now create the account, and store record.id and record.receipt with it.
return { confirmed: true, recordId: record.id };
});
const port = Number(process.env.PORT ?? 3000);
await app.listen({ port });
console.log(`http://localhost:${port}/signup`);
Fastify does two things here that you write yourself in other frameworks. It parses the JSON body, so there is no body parser to add. And the schema on the confirm route refuses a body without recordId before the handler runs.
The signer is a fixed test person here. In your app it is request.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.
Start the server:
node --env-file=.env server.js
http://localhost:3000/signup
Step 5. Attach the ceremony in the browser
The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as public/signup.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Create account</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
a { color: #0b57d0; text-decoration: underline; }
button { font: inherit; padding: 10px 16px; }
</style>
</head>
<body>
<h1>Create account</h1>
<form id="signup">
<div id="assent">
<!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
<label><input id="agree" type="checkbox" disabled /> 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 id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
<a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
</p>
<button id="create-account" type="submit" disabled>Create account</button>
</div>
<p id="message" role="alert"></p>
</form>
<script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
<script type="module">
const agree = document.querySelector("#agree");
const submit = document.querySelector("#create-account");
const message = document.querySelector("#message");
// Your server creates the session and returns only the client token and the pinned documents.
const response = await fetch("/api/ceremony", { method: "POST" });
const { clientToken, apiUrl, documents } = await response.json();
const ceremony = await EsignComply.attach({ clientToken, apiUrl });
ceremony.on("change", ({ remainingSteps }) => {
submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
});
// Point each link at the exact version this session pinned, then report it.
const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
for (const [i, link] of links.entries()) {
link.search = "?v=" + documents[i].version_id;
await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
}
await ceremony.observeAssent({
region: document.querySelector("#assent"), // notice, links, checkbox, button
checkbox: agree,
submit,
});
agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.
document.querySelector("#signup").addEventListener("submit", async (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 }),
});
message.textContent = confirmed.ok
? `Account created. Record ${result.recordId}`
: "We could not confirm whether your acceptance was recorded. Please wait while we check.";
} catch (error) {
message.textContent = error.message;
}
});
</script>
</body>
</html>
Open http://localhost:3000/signup. The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows a line such as:
Account created. Record rec_DZva0qrFLivHpKA6VSqV
The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it: 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 page asks for the session with a POST that has no body and no content type. Keep it that way: Fastify answers 400 to a request that names application/json and sends nothing.
Step 6. Confirm the record on the server
The result of complete() was delivered to the browser, so your server does not trust it. app.post("/api/signup/confirm") 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_DZva0qrFLivHpKA6VSqV (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}
A body without recordId does not reach the handler. The schema answers 400:
{"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"body must have required property 'recordId'"}
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_DZva0qrFLivHpKA6VSqV session ses_8ttDMmY6KoXP7WX6CEBD, 5 events
768x1024 record rec_AD5XvHVSNJcLkcBHXrTZ session ses_FwxafV4F37euhVoH98hY, 5 events
1440x900 record rec_SfLFv2ej1qbt6eWmej9M session ses_4XHLF2hAkKyvgfDrNVuH, 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. - In a container, pass a host:
app.listen({ port, host: "0.0.0.0" }). Fastify listens on127.0.0.1by default, where nothing outside the container reaches it. - Replace the
pinnedMap with a table in your database, and storerecord.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
FST_ERR_CTP_EMPTY_JSON_BODYfrom/api/ceremony. The request namedContent-Type: application/jsonand sent no body. Fastify refuses it with400before your handler runs, so no session is created and the browser SDK has nothing to attach to. Send no content type with an emptyPOST, or send{}.missing_api_keyfrom/api/ceremony. The server was started without--env-file=.env, so the SDK found no key. The SDK does not throw when the key is missing: every call resolves with this error and the route answers502. Seemissing_api_key.domain_mismatchwhen the page loads. The page was opened from a host that is not on the test allowlist, for example your machine's LAN address or a tunnel. 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 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 Fastify quickstart
Does Fastify need a body parser for the confirm route?
No. Fastify parses application/json bodies itself, so request.body is an object with no plugin added. The quickstart was run on Fastify 5.12.8, and the confirm route read recordId straight from it.
What does the JSON schema on the confirm route add?
It refuses a malformed request before the handler and before any API call. In the test run, a body without recordId was answered 400 with FST_ERR_VALIDATION, and a body with a made-up record ID reached the handler and was refused with 409.
Why did my empty POST get a 400 from Fastify?
Because it named Content-Type: application/json and had no body. Fastify answered 400 with FST_ERR_CTP_EMPTY_JSON_BODY in the test. The same POST with no content type and no body, which is what the signup page sends, was answered 200.
Why can nothing outside my machine reach the server?
Because Fastify listens on 127.0.0.1 unless you pass a host. In a test, a request through the machine's own network address was refused, and the same request succeeded once the server listened with host: "0.0.0.0".
Does the Fastify 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 Fastify: what the integration gives you on this stack, with the things to watch for.
- Server confirmation: the checks in step 6 and the
record.completedwebhook. - Node SDK: every method, the endpoint it calls, and the errors.
- Add e-signatures and clickwrap with Express: the same flow with Express routes and middleware.
- All quickstarts.
Run on 2026-11-26 with Fastify 5.12.8 and @fastify/static 10.1.12 on Node.js 24.22.1, esigncomply 1.0.4, the browser SDK script build and the conformance check from esigncomply 1.0.4 (--timeout 60), against the API in test mode.
Last updated · API version 2026-11-21