# Add e-signatures and clickwrap on Cloudflare Pages

> Run a signup clickwrap on Cloudflare Pages with Pages Functions, the esigncomply package, the key as a secret, and a D1 table for the receipt.

Source: https://esigncomply.com/docs/quickstart/cloudflare-pages

Last updated November 26, 2026

To add e-signatures and clickwrap on Cloudflare Pages, put the server calls in Pages Functions: files under `functions/` that create the session and confirm the record with the `esigncomply` package. The secret key is a Pages secret, the signup page is a static file, and a D1 table keeps the receipt. 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:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Cloudflare Pages project: 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/cloudflare-pages.md (the steps and the tested code for Cloudflare Pages)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Cloudflare Pages facts
- Packages (the only ones that exist): esigncomply (server) and @esigncomply/browser. The esigncomply package runs in Pages Functions: create the client per request with new EsignComply(context.env.ESIGNCOMPLY_API_KEY).
- Server code lives in the functions folder at the project root, one file per route: functions/api/ceremony.js answers /api/ceremony. Shared code sits outside that folder.
- The secret key is a Pages secret: npx wrangler pages secret put ESIGNCOMPLY_API_KEY for the project, a .dev.vars file for wrangler pages dev. Never put it under vars in the Wrangler configuration file. Never print it.
- Two requests can run in two isolates. Keep the pinned version IDs in D1, never in a module-level variable.
- Preview deployments run on <hash>.<project>.pages.dev and <branch>.<project>.pages.dev. One test origin, <project>.pages.dev, covers them all.
- 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. Function functions/api/ceremony.js (onRequestPost): create the session with esc.sessions.create and an Idempotency-Key, save the signer ID and the pinned version IDs in D1, and return only clientToken, apiUrl and documents.
4. Function functions/legal/[slug].js (onRequestGet): render 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. Function functions/api/signup/confirm.js (onRequestPost): 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 row in D1. Only then create the account, and store the record ID and the receipt in the same row.

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:8788/signup --callback http://localhost:8788/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. Steps 1 to 7 run on your machine with `wrangler pages dev`. Step 8 is the part that happens on Cloudflare.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) 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](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- Node.js 20.19 or later for Wrangler and the conformance check. This page was run with Wrangler 4.168.0.
- A Cloudflare account, when you reach step 8. Steps 1 to 7 need none: `wrangler pages dev` runs the Functions and D1 on your machine.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Install the `esigncomply` server package and Wrangler, the command line tool that runs Pages Functions on your machine and deploys the project:

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
npm init -y && npm pkg set type=module
npm install esigncomply
npm install --save-dev wrangler
mkdir -p functions/api/signup functions/legal lib public
```

The `functions` folder sits at the root of the project, beside `public`, not inside it. The `esigncomply` package is written for Node.js, and it also runs in Pages Functions: every call on this page was made from a Function under `wrangler pages dev`.

## Step 2. Set the key

On your machine the key goes in `.dev.vars`, in the same folder as the Wrangler configuration file. `wrangler pages dev` reads it and passes each line to your Functions on `context.env`. On Cloudflare the key is a secret of the Pages project, added in step 8. It never goes under `vars`, which is plain text in a file you commit.

```bash
# .dev.vars (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:

```bash
set -a; . ./.dev.vars; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "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`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/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`.

```bash
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:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.dev.vars`. 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](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

The Wrangler configuration file names the project, the folder of static files and the D1 database. The key `pages_build_output_dir` is what makes it a Pages configuration.

```jsonc file="wrangler.jsonc"
// wrangler.jsonc
{
  "name": "esigncomply-quickstart",
  // This key makes the file a Pages configuration: the folder of static files to publish.
  "pages_build_output_dir": "./public",
  "compatibility_date": "2026-11-01",
  // D1 keeps what the session pinned, then the record ID and the receipt.
  // Local development accepts any database_id. Before you deploy, run
  // `npx wrangler d1 create esigncomply-quickstart` and paste the ID it prints.
  "d1_databases": [
    { "binding": "DB", "database_name": "esigncomply-quickstart", "database_id": "00000000-0000-0000-0000-000000000000" }
  ],
  // Plain text, so never a key. Preview deployments keep "false".
  "vars": { "ESIGNCOMPLY_LIVE": "false" }
}
```

Two requests can run in two isolates, so what the session pinned cannot sit in a variable. It goes in a D1 table, which later holds the record ID and the receipt as well:

```sql file="schema.sql"
-- schema.sql
CREATE TABLE IF NOT EXISTS acceptances (
  signer_id   TEXT PRIMARY KEY,  -- signer.external_id sent to Esign Comply
  version_ids TEXT NOT NULL,     -- JSON array: the versions the session pinned
  record_id   TEXT,              -- rec_..., set once the record is confirmed
  receipt     TEXT,              -- the signed receipt (JWS, ES256)
  accepted_at TEXT
);
```

Create the table in the local database:

```bash
npx wrangler d1 execute esigncomply-quickstart --local --file=schema.sql
```

On Pages every file under `functions/` is a route, so the code the three routes share sits outside it. Secrets and variables arrive on `context.env` with each request, so the client is made per request:

```js file="lib/esigncomply.js"
// lib/esigncomply.js
import { EsignComply } from "esigncomply";

export const SEALED = ["recorded", "timestamped", "anchored"];

// 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",
};

// Secrets and variables arrive on context.env with each request, so the client is made per request.
export function client(env) {
  return new EsignComply(env.ESIGNCOMPLY_API_KEY, { baseUrl: env.ESIGNCOMPLY_API_URL });
}

export function documents(env) {
  return { terms: env.ESIGNCOMPLY_TERMS_ID, privacy: env.ESIGNCOMPLY_PRIVACY_ID };
}
```

`functions/api/ceremony.js` answers `POST /api/ceremony`: the file path is the route, and `onRequestPost` is the method. It creates the session and returns three values to the browser: the client token, the API URL and the pinned documents.

```js file="functions/api/ceremony.js"
// functions/api/ceremony.js
import { client, documents, signer } from "../../lib/esigncomply.js";

// Step 4: create the session with the secret key. The browser gets the client token only.
export async function onRequestPost({ request, env }) {
  const docs = documents(env);
  const { data: session, error } = await client(env).sessions.create(
    {
      profile: env.ESIGNCOMPLY_PROFILE_ID,
      signer,
      documents: [
        { document: docs.terms, version: "current" },
        { document: docs.privacy, version: "current" },
      ],
      // The deployment that served the page: localhost, a preview on pages.dev or your own domain.
      context: { url: `${new URL(request.url).origin}/signup`, locale: "en-US", purpose: "account_signup" },
    },
    { idempotencyKey: `signup-${signer.external_id}-${crypto.randomUUID()}` },
  );
  if (error) return Response.json({ error: error.code }, { status: 502 });

  // Two requests can run in two isolates, so what this Function pinned goes to D1, not to memory.
  const versionIds = JSON.stringify(session.documents.map((d) => d.version_id).sort());
  await env.DB.prepare(
    "INSERT INTO acceptances (signer_id, version_ids) VALUES (?1, ?2) ON CONFLICT (signer_id) DO UPDATE SET version_ids = ?2, record_id = NULL, receipt = NULL, accepted_at = NULL",
  )
    .bind(signer.external_id, versionIds)
    .run();
  return Response.json({ clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });
}
```

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 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`. Pages serves it at `/signup`.

```html file="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>
```

Each link opens a document page on the same origin. A Function with a dynamic segment renders the registered version, unmodified:

```js file="functions/legal/[slug].js"
// functions/legal/[slug].js
import { client, documents } from "../../lib/esigncomply.js";

// The document pages: /legal/terms?v=dv_... renders one registered version, unmodified.
export async function onRequestGet({ request, env, params }) {
  const documentId = documents(env)[params.slug];
  if (!documentId) return Response.json({ error: "not_found" }, { status: 404 });
  const { data, error } = await client(env).documents.versions.getContent(documentId, new URL(request.url).searchParams.get("v") ?? "current");
  if (error) return Response.json({ error: error.code }, { status: 404 });
  return new Response(`<!doctype html><meta charset="utf-8"><article data-esc-document="${data.version_id}">${data.html}</article>`, {
    headers: { "Content-Type": "text/html; charset=utf-8" },
  });
}
```

Start the project and open the address Wrangler prints, [http://localhost:8788/signup](http://localhost:8788/signup) by default:

```bash
npx wrangler pages dev
```

```text
Using secrets defined in .dev.vars
env.DB (esigncomply-quickstart)                 D1 Database               local
env.ESIGNCOMPLY_LIVE ("false")                  Environment Variable      local
env.ESIGNCOMPLY_API_KEY ("(hidden)")            Environment Variable      local
```

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](https://esigncomply.com/docs/conformance.md#cr-01). In a test with the session request held back, a click on the box did nothing. The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_1TpAujJuUqVGKyqxpxFs
```

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so the Function does not trust it. `functions/api/signup/confirm.js` reads the record with the secret key and the row from D1, 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 the session was created for; and the document versions are exactly the ones it pinned. This step is never optional.

```js file="functions/api/signup/confirm.js"
// functions/api/signup/confirm.js
import { client, SEALED, signer } from "../../../lib/esigncomply.js";

// Step 6: confirm the record with the secret key before the account exists.
export async function onRequestPost({ request, env }) {
  const { recordId } = await request.json();
  const { data: record, error } = await client(env).records.get(String(recordId));
  const row = await env.DB.prepare("SELECT version_ids FROM acceptances WHERE signer_id = ?1").bind(signer.external_id).first();
  const confirmed =
    !error &&
    row !== null &&
    SEALED.includes(record.status) &&
    record.livemode === (env.ESIGNCOMPLY_LIVE === "true") &&
    record.signer.external_id === signer.external_id &&
    JSON.stringify(record.documents.map((d) => d.version_id).sort()) === row.version_ids;
  console.log(confirmed ? `confirmed ${record.id} (${record.status})` : "refused");
  if (!confirmed) return Response.json({ confirmed: false }, { status: 409 });

  // Only now create the account. The record ID and the receipt stay in your own table.
  await env.DB.prepare("UPDATE acceptances SET record_id = ?2, receipt = ?3, accepted_at = ?4 WHERE signer_id = ?1")
    .bind(signer.external_id, record.id, record.receipt, record.signed_at)
    .run();
  return Response.json({ confirmed: true, recordId: record.id });
}
```

`wrangler pages dev` prints one line for each confirmation:

```text
confirmed rec_1TpAujJuUqVGKyqxpxFs (timestamped)
```

The row then holds the record ID and the receipt:

```bash
npx wrangler d1 execute esigncomply-quickstart --local \
  --command "SELECT signer_id, record_id, substr(receipt, 1, 12) AS receipt_start, accepted_at FROM acceptances"
```

```json
{
  "signer_id": "user_7c1d",
  "record_id": "rec_1TpAujJuUqVGKyqxpxFs",
  "receipt_start": "eyJhbGciOiJF",
  "accepted_at": "2026-11-26T09:54:22.239Z"
}
```

A record ID that was made up is refused with status `409` and `{"confirmed":false}`. See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) 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.

```bash
npm install --save-dev playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:8788/signup --callback http://localhost:8788/api/signup/confirm
```

The report for this page's code, shortened:

```text
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:8788/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_EqFa6PYPi9akjFSku2aQ  session ses_QQinajs1DrEEqagabmDc, 5 events
  768x1024   record rec_1aqZ7kyeFmQdntRH1fJY  session ses_XACtsXk9HpQu13CarEaY, 5 events
  1440x900   record rec_KNTQk9Lyhg29HrEwP6cp  session ses_sg2orRKMZidneeBZmGiu, 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](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## 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](https://esigncomply.com/docs/guides/domains.md).
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 set up the project on Cloudflare. The settings below are from Cloudflare's own documentation, checked on November 24, 2026: [Pages Functions bindings](https://developers.cloudflare.com/pages/functions/bindings/), [Pages Functions Wrangler configuration](https://developers.cloudflare.com/pages/functions/wrangler-configuration/), [Preview deployments](https://developers.cloudflare.com/pages/configuration/preview-deployments/) and [the Pages commands of Wrangler](https://developers.cloudflare.com/workers/wrangler/commands/pages/).

**The database.** `wrangler pages dev` uses a local database, so the deployed project needs its own database and its own table:

```bash
npx wrangler d1 create esigncomply-quickstart   # prints the database_id for wrangler.jsonc
npx wrangler d1 execute esigncomply-quickstart --remote --file=schema.sql
```

**The secrets.** In the dashboard, open the project and choose Settings, then Variables and Secrets, then Add: the live key and the live IDs for the production environment, the test key and the test IDs for the preview environment. From the command line, `npx wrangler pages secret put ESIGNCOMPLY_API_KEY --project-name esigncomply-quickstart` adds one secret. Set them before the deployment that uses them.

**Production.** Production alone expects live records. In the Wrangler file, `vars` and bindings are not inherited by an environment override: an `env.production` block that sets `ESIGNCOMPLY_LIVE` has to repeat `d1_databases` as well, or the file fails to validate when you deploy.

```jsonc
  "env": {
    "production": {
      "d1_databases": [
        { "binding": "DB", "database_name": "esigncomply-quickstart", "database_id": "<your database_id>" }
      ],
      "vars": { "ESIGNCOMPLY_LIVE": "true" }
    }
  }
```

Then deploy with `npx wrangler pages deploy`.

**Preview deployments.** Every branch gets an address of the form `<hash>.<project>.pages.dev` and an alias, `<branch>.<project>.pages.dev`. A test key refuses a host it does not know with [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch). List `<project>.pages.dev` once under Domains in the dashboard, or with the API: an entry also covers its subdomains, so it covers every preview of the project.

```bash
curl -X PATCH https://esigncomply.com/v1/domains/dom_4Kx9 \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" -H "Content-Type: application/json" \
  -d '{ "test_origins": ["my-app.pages.dev"] }'
```

In a test against the API, a session for `https://373f31e2.my-app.pages.dev` was refused before that entry existed, and accepted after it, as was one for `https://fix-api.my-app.pages.dev`. A host of another project stayed refused. Never list the shared suffix `pages.dev`.

**The production domain.** Register your custom domain and verify it with one DNS record. If production runs on its `pages.dev` host, you cannot add DNS records there, so the domain verifies with a file: put the token in `public/.well-known/esigncomply.txt`. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).

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

- **`missing_api_key` from `/api/ceremony`.** `context.env.ESIGNCOMPLY_API_KEY` is empty. Locally, the `.dev.vars` file is missing or sits in another folder than the Wrangler configuration file. On Cloudflare, the secret was not added for the environment the deployment runs in, production or preview. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`domain_mismatch` on a preview deployment.** The preview's host is not a test origin of your domain. Add `<project>.pages.dev` under Domains in the dashboard: one entry covers every preview. Test keys work on `localhost` with no setup. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **The confirm route answers `409` for a real record.** The row with the pinned versions is not in the database the Function reads. The local database and the deployed one are two databases: apply `schema.sql` to both, and check that the binding is named `DB`. A record ID that does not exist fails the same way, with [`not_found`](https://esigncomply.com/docs/api/errors.md#not_found).
- **`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, inside the Function. In the test, four confirmations sent at once for one record all answered `200`, two of them about a second later than the others. Four reads sent at once through the package in a Function showed why: two got `429` with `Retry-After: 1` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded) and [Retries and timeouts](https://esigncomply.com/docs/sdk/node.md#retries-and-timeouts).

## Questions about the Cloudflare Pages quickstart

### How is the Cloudflare Pages quickstart different from the Workers one?

The server code is split by route. On Pages each file under `functions/` answers the path it sits at, with handlers such as `onRequestPost`, and reads secrets from `context.env`. On Workers one `fetch` handler does the routing. The package, the D1 table and the page are the same.

### Where does the secret key go on Cloudflare Pages?

In a secret of the Pages project, set for production and for preview separately, with the live key in production only. Locally it goes in `.dev.vars`. Do not put it under `vars` in the Wrangler configuration file: that file is plain text and is committed.

### Does every preview deployment need a test origin of its own?

No. Preview hosts are subdomains of the project's host, and a test origin covers its subdomains. In a test, one entry for `my-app.pages.dev` let sessions through for a hash address and for a branch alias of that project, and a host of another project stayed refused.

### Why does the shared code sit outside the functions folder?

Because on Pages the path of a file under `functions/` is its route. Code that three routes share is not a route, so it lives in `lib/` and each Function imports it. In a test, a file with no handler placed under `functions/` answered `404` at its path.

### Do I need a Cloudflare account to run the quickstart?

No. `wrangler pages dev` runs the Functions and D1 on your machine, and it accepted a placeholder `database_id` when this page was tested. You need an account to create the remote database, add the secrets and deploy.

### Was this quickstart deployed to Cloudflare Pages?

Not yet. The code was run with `wrangler pages dev` on Wrangler 4.168.0, and the Cloudflare settings come from Cloudflare's documentation as of November 24, 2026. The deployed Functions, the secrets per environment, the remote D1 database and file verification on a `pages.dev` host are proven only by a deployment.

## Next steps

- [E-signatures and clickwrap on Cloudflare Pages](https://esigncomply.com/cloudflare-pages): how the pieces fit on this platform, with the things to watch for.
- [Add e-signatures and clickwrap on Cloudflare Workers](https://esigncomply.com/docs/quickstart/cloudflare-workers.md): the same flow in one Worker with a `fetch` handler.
- [Register a domain](https://esigncomply.com/docs/guides/domains.md): DNS and file verification, statuses, and test origins.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
