# Add e-signatures and clickwrap on Supabase

> Run a signup clickwrap on Supabase with two Edge Functions, the key as a function secret, and a Postgres table with row level security for the receipt.

Source: https://esigncomply.com/docs/quickstart/supabase

Last updated November 26, 2026

To add e-signatures and clickwrap on Supabase, keep the secret key as an Edge Function secret. One Edge Function creates the session with a plain `fetch` call, a second confirms the record, and a Postgres table with row level security holds what the session pinned, then 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, Lovable or another AI coding tool to have it build the same integration:

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

Supabase facts
- There is no Esign Comply package for Deno. Edge Functions call the REST API at https://esigncomply.com/v1 with fetch, Authorization: Bearer and the secret key. Do not install or invent a package.
- The secret key is an Edge Function secret: supabase secrets set ESIGNCOMPLY_API_KEY=... for the project, supabase/functions/.env for local runs. Read it with Deno.env.get. A secret name cannot start with SUPABASE_. Never print the key, and never put it in the front end.
- The browser calls the functions from another origin: answer the OPTIONS preflight and send the CORS headers on every response.
- Edge Functions on a supabase.co address cannot serve HTML, so the documents are not Edge Function pages. Render each pinned version in the page: the content endpoint accepts the session's client token.
- Keep the pinned version IDs, the record ID and the receipt in a Postgres table with row level security and no policies. Only the Edge Functions write it, with the secret key client.
- 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. Edge Function ceremony: POST /v1/sessions with an Idempotency-Key, upsert the signer ID and the pinned version IDs into the table, and return only clientToken, apiUrl and documents.
4. Browser: EsignComply.attach({ clientToken, apiUrl }). For each document, fetch GET {apiUrl}/documents/{document_id}/versions/{version_id}/content with the client token, inject the html unmodified into an element marked data-esc-document, and call presentDocument({ versionId, mode: "inline", container }). Then observeAssent({ region, checkbox, submit }) and complete() from the user's real click.
5. Edge Function confirm: GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the row. Only then create the account, and store the record ID and the receipt in the 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 Edge Function 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 https://YOUR-PROJECT.supabase.co/functions/v1/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](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.
- A Supabase project and the Supabase CLI, to run and deploy the functions and to create the table.
- A front end on any host. This page uses one static HTML file.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

No package needed in the functions. The server SDK exists for Node.js only, and Edge Functions run on Deno, so the two functions call the REST API with `fetch`. They load `@supabase/supabase-js` with an `npm:` import, and the page loads the browser SDK from a script tag.

```bash
supabase functions new ceremony
supabase functions new confirm
mkdir -p supabase/functions/_shared public
```

## Step 2. Set the key

The key is an Edge Function secret. For local runs it goes in `supabase/functions/.env`. For the project, set it with `supabase secrets set` in step 8. Functions read it with `Deno.env.get`. A secret name cannot start with `SUPABASE_`: that prefix is reserved for the variables Supabase injects.

```bash
# supabase/functions/.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:

```bash
set -a; . ./supabase/functions/.env; 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 `supabase/functions/.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](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

Two Edge Functions run in two workers and share no memory, so what the session pinned goes in a Postgres table. The same row later holds the record ID and the receipt. Row level security is on and there are no policies: the publishable key in the browser can read and write nothing, and only the Edge Functions write the table.

```sql file="supabase/migrations/20261123000000_acceptances.sql"
-- supabase/migrations/20261123000000_acceptances.sql
create table public.acceptances (
  signer_id   text primary key,     -- signer.external_id sent to Esign Comply
  version_ids text[] not null,      -- the versions the session pinned
  record_id   text unique,          -- rec_..., set once the record is confirmed
  receipt     text,                 -- the signed receipt (JWS, ES256)
  accepted_at timestamptz
);

-- Row level security with no policies: the anon and authenticated roles read and write nothing.
-- Edge Functions use the service role, which bypasses row level security.
alter table public.acceptances enable row level security;
```

```bash
supabase db push
```

One shared module holds the API call, the admin client and the test signer:

```ts file="supabase/functions/_shared/esigncomply.ts"
// supabase/functions/_shared/esigncomply.ts
import { createClient } from "npm:@supabase/supabase-js@2";
export { corsHeaders } from "npm:@supabase/supabase-js@^2/cors";

// There is no Esign Comply package for Deno: the server calls are plain fetch calls with the secret key.
const API = Deno.env.get("ESIGNCOMPLY_API_URL") ?? "https://esigncomply.com/v1";

// On 429 the API names the wait in Retry-After: wait that long, 5 seconds at most, and send the
// request again, twice at most. Nothing else is retried.
export async function esc(path: string, init: RequestInit = {}) {
  for (let attempt = 0; ; attempt++) {
    const response = await fetch(API + path, {
      ...init,
      headers: { Authorization: `Bearer ${Deno.env.get("ESIGNCOMPLY_API_KEY")}`, "Content-Type": "application/json", ...init.headers },
    });
    if (response.status === 429 && attempt < 2) {
      await response.body?.cancel();
      const seconds = Math.min(Math.max(Number(response.headers.get("Retry-After")) || 1, 1), 5);
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
      continue;
    }
    return { ok: response.ok, data: await response.json() };
  }
}

// The admin client bypasses row level security. It exists only inside Edge Functions.
const SECRET_KEYS = JSON.parse(Deno.env.get("SUPABASE_SECRET_KEYS")!);
export const admin = createClient(Deno.env.get("SUPABASE_URL")!, SECRET_KEYS["default"]);

// The signer. In your app this is the Supabase Auth user: read it from the request's JWT.
export const signer = {
  external_id: "user_7c1d",
  email: "dana@example.org",
  name: "Dana Whitfield",
  class: "consumer",
  country: "US",
  region: "US-CA",
};
```

When the API answers `429`, `esc` waits for the seconds in `Retry-After`, 5 at most, and sends the request again, up to twice. Nothing else is retried.

The first function creates the session. It answers the `OPTIONS` preflight and sends the CORS headers on every response, because the browser calls it from another origin. It returns three values: the client token, the API URL and the pinned documents.

```ts file="supabase/functions/ceremony/index.ts"
// supabase/functions/ceremony/index.ts
import { admin, corsHeaders, esc, signer } from "../_shared/esigncomply.ts";

// Step 4: create the session with the secret key. The browser gets the client token only.
Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  const { ok, data: session } = await esc("/sessions", {
    method: "POST",
    headers: { "Idempotency-Key": `signup-${signer.external_id}-${crypto.randomUUID()}` },
    body: JSON.stringify({
      profile: Deno.env.get("ESIGNCOMPLY_PROFILE_ID"),
      signer,
      documents: [
        { document: Deno.env.get("ESIGNCOMPLY_TERMS_ID"), version: "current" },
        { document: Deno.env.get("ESIGNCOMPLY_PRIVACY_ID"), version: "current" },
      ],
      // The page lives on your front end's host, not on the function's: take it from the Origin header.
      context: { url: `${req.headers.get("origin")}/signup`, locale: "en-US", purpose: "account_signup" },
    }),
  });
  if (!ok) return Response.json({ error: session.error?.code }, { status: 502, headers: corsHeaders });

  // What this function pinned goes to Postgres: the confirm function runs in another worker.
  const { error } = await admin.from("acceptances").upsert({
    signer_id: signer.external_id,
    version_ids: session.documents.map((d: { version_id: string }) => d.version_id).sort(),
    record_id: null,
    receipt: null,
    accepted_at: null,
  });
  if (error) return Response.json({ error: "storage_failed" }, { status: 500, headers: corsHeaders });

  return Response.json(
    { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents },
    { headers: corsHeaders },
  );
});
```

The signer is a fixed test person here. In your app it is the Supabase Auth user, read from the JWT of the request.

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice and the button you built, and reports each step from the signer's browser straight to Esign Comply.

This page has no server of its own, and Edge Functions on a `supabase.co` address cannot serve HTML. So the documents are not separate pages: the page renders each pinned version in place. It reads the content with the session's client token, which the content endpoint accepts for the versions of that session.

Save the page as `public/signup.html` and set the two public values at the top of the script: your project URL and its publishable key.

```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; }
      article { border: 1px solid #c4c7c5; border-radius: 8px; padding: 0 16px; margin: 0 0 12px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="documents"></div>
      <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 href="#doc-0">Terms of Service</a> and acknowledge the <a href="#doc-1">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">
      import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

      // Public values: your project URL and its publishable key. The secret key stays in the Edge Function.
      const supabase = createClient("https://YOUR-PROJECT.supabase.co", "YOUR-PUBLISHABLE-KEY");
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // The Edge Function creates the session and returns only the client token and the pinned documents.
      const { data, error } = await supabase.functions.invoke("ceremony", { method: "POST" });
      if (error) throw error;
      const { clientToken, apiUrl, documents } = data;

      const ceremony = await EsignComply.attach({ clientToken, apiUrl });
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });

      // This page has no server of its own, so it renders each pinned version in place.
      // The content endpoint accepts the session's client token for the versions of that session.
      for (const [i, doc] of documents.entries()) {
        const response = await fetch(`${apiUrl}/documents/${doc.document_id}/versions/${doc.version_id}/content`, {
          headers: { Authorization: `Bearer ${clientToken}` },
        });
        const article = document.createElement("article");
        article.id = `doc-${i}`;
        article.dataset.escDocument = doc.version_id;
        article.innerHTML = (await response.json()).html; // sanitized by Esign Comply: inject it unmodified
        document.querySelector("#documents").append(article);
        await ceremony.presentDocument({ versionId: doc.version_id, mode: "inline", container: article });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, 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. The Edge Function confirms the record before anything is granted.
          const confirmed = await supabase.functions.invoke("confirm", { body: { recordId: result.recordId } });
          message.textContent = confirmed.error
            ? "We could not confirm whether your acceptance was recorded. Please wait while we check."
            : `Account created. Record ${result.recordId}`;
        } catch (err) {
          message.textContent = err.message;
        }
      });
    </script>
  </body>
</html>
```

Serve the functions and the page, then open [http://localhost:3000/signup](http://localhost:3000/signup):

```bash
supabase functions serve --env-file supabase/functions/.env
npx serve public
```

Both documents appear above the checkbox. 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_Co2VPYJRJqSuiXQCxUiB
```

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so the function does not trust it. The second Edge Function reads the record with the secret key and the row from Postgres, and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this project 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.

```ts file="supabase/functions/confirm/index.ts"
// supabase/functions/confirm/index.ts
import { admin, corsHeaders, esc, signer } from "../_shared/esigncomply.ts";

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

// Step 6: confirm the record with the secret key before the account exists.
Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });

  const { recordId } = await req.json();
  const { ok, data: record } = await esc(`/records/${encodeURIComponent(String(recordId))}`);
  const { data: row } = await admin.from("acceptances").select("version_ids").eq("signer_id", signer.external_id).maybeSingle();

  const confirmed =
    ok &&
    row !== null &&
    SEALED.includes(record.status) &&
    record.livemode === (Deno.env.get("ESIGNCOMPLY_LIVE") === "true") &&
    record.signer.external_id === signer.external_id &&
    JSON.stringify(record.documents.map((d: { version_id: string }) => d.version_id).sort()) === JSON.stringify(row.version_ids);
  console.log(confirmed ? `confirmed ${record.id} (${record.status})` : "refused");
  if (!confirmed) return Response.json({ confirmed: false }, { status: 409, headers: corsHeaders });

  // Only now create the account. The record ID and the receipt stay in your own table.
  const { error } = await admin
    .from("acceptances")
    .update({ record_id: record.id, receipt: record.receipt, accepted_at: record.signed_at })
    .eq("signer_id", signer.external_id);
  // A receipt that was not stored is not confirmed: the page shows its "could not confirm" sentence.
  if (error) {
    console.error(`not stored: ${error.message}`);
    return Response.json({ error: "storage_failed" }, { status: 500, headers: corsHeaders });
  }
  return Response.json({ confirmed: true, recordId: record.id }, { headers: corsHeaders });
});
```

The function logs one line for each confirmation:

```text
confirmed rec_Co2VPYJRJqSuiXQCxUiB (recorded)
```

The row then holds the record ID and the receipt:

```sql
select signer_id, version_ids, record_id, left(receipt, 12), accepted_at from public.acceptances;
```

```text
user_7c1d|{dv_kiCAswKyHr5CSHeZCiZ3,dv_vEKJCHuUSXr0DVmWdQTE}|rec_Co2VPYJRJqSuiXQCxUiB|eyJhbGciOiJF|2026-11-26 16:08:15.722+00
```

When that write fails, the function answers `500` with `storage_failed`, so nothing is confirmed that was not stored. In a test with the write made to fail, the page showed its "could not confirm" sentence and the row kept no record ID.

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 function 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. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:3000/signup --callback https://YOUR-PROJECT.supabase.co/functions/v1/confirm
```

Use the address of your own `confirm` function as the callback. 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  https://YOUR-PROJECT.supabase.co/functions/v1/confirm answered 409.

Ceremonies
  390x844    record rec_QJYHCGAcQr5hKurMedw0  session ses_QV4cbHyJBRLN0HTsujev, 5 events
  768x1024   record rec_LwPgCWVMargkXqh32Waq  session ses_wGkhtM2WEGC5CqkZ9un2, 5 events
  1440x900   record rec_R1vHHdNZNAcxRrBaG0KX  session ses_voAoJRuqBkYuX4gUteN4, 5 events

Summary: 0 block, 0 warn, 24 pass.
```

The summary counts 24 passes where the quickstarts with document links count 27: this page shows the documents in place.

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 Supabase project. The settings below are from Supabase's own documentation, checked on November 23, 2026: [Environment variables](https://supabase.com/docs/guides/functions/secrets), [CORS](https://supabase.com/docs/guides/functions/cors) and [Edge Functions limits](https://supabase.com/docs/guides/functions/limits).

**The secrets.** Set the live key and the live IDs on the production project, and `ESIGNCOMPLY_LIVE=true` there only. Functions read a new secret at once, with no redeploy.

```bash
supabase secrets set ESIGNCOMPLY_API_KEY=esc_live_us_... ESIGNCOMPLY_LIVE=true
supabase secrets set ESIGNCOMPLY_PROFILE_ID=prof_... ESIGNCOMPLY_TERMS_ID=doc_... ESIGNCOMPLY_PRIVACY_ID=doc_...
supabase functions deploy ceremony
supabase functions deploy confirm
```

`SUPABASE_URL` and `SUPABASE_SECRET_KEYS` are injected by Supabase: you do not set them.

**The domain.** The ceremony runs on your front end's host, not on the `supabase.co` address of the functions, so the domain you register with Esign Comply is the front end's. The first function takes `context.url` from the `Origin` header for that reason. A preview of the front end on another host keeps the test key, and its exact host goes under Domains in the dashboard as a test origin. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).

**The signer.** Replace the fixed signer with the Supabase Auth user. Pass the user's JWT to the function, read the user from it, and use the user's ID as `external_id`. The identity is asserted by your app from the auth session, which is level L1.

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

- **A CORS error in the browser console and no session.** The function did not answer the `OPTIONS` preflight, or a response left without the CORS headers. Send `corsHeaders` on every response, errors included. A function that throws looks the same in the console: in the test the Edge Runtime answered `500` without the headers, so read the function's log to see how far the request got.
- **`domain_mismatch` from the ceremony function.** `context.url` names a host that is not on the test allowlist. The function takes it from the `Origin` header, so this is the host of your front end. Test keys work on `localhost` with no setup. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`invalid_api_key` or `missing_api_key` from a deployed function.** The secret is set for local runs only. Run `supabase secrets set ESIGNCOMPLY_API_KEY=...` for the project. See [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key).
- **`429` when the confirm function reads the record.** `esc` waits for the seconds in `Retry-After`, 5 at most, and sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once for one record all answered `200`, two of them about 1.5 seconds later than the others. Four reads sent at once through `esc` showed why: two got `429` with `Retry-After: 1` and passed on the next attempt. Without the retry, the same four confirmations ended with two `409` for a real record. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded).

## Questions about the Supabase quickstart

### Can a Supabase Edge Function use the esigncomply package?

The quickstart does not use it. The server SDK is built for Node.js and Edge Functions run on Deno, so the two functions call the REST API with `fetch`: one `POST` to create the session and one `GET` to read the record.

### Where is the receipt stored on Supabase?

In a Postgres table, `acceptances`, beside the signer ID and the pinned version IDs. Row level security is on with no policies, so the publishable key reads and writes nothing. In a test, an insert with that key was refused by the row level security policy.

### Why are the documents shown inside the page?

Because nothing on Supabase can serve them as pages for this app. Edge Functions on a `supabase.co` address cannot serve HTML, and the page has no server of its own. The content endpoint accepts the session's client token, so the page fetches each pinned version and renders it in place.

### Why do the Edge Functions need CORS headers?

Because the browser calls them from another origin: your front end's host. The function answers the `OPTIONS` preflight and sends the headers on every response. The quickstart imports `corsHeaders` from `@supabase/supabase-js`, as Supabase's CORS guide shows.

### Was this quickstart deployed to a hosted Supabase project?

Not yet. The functions ran on the Edge Runtime, PostgREST and Postgres images of the Supabase local stack, started on their own, and the settings come from Supabase's documentation as of November 23, 2026. `supabase db push`, `supabase secrets set`, `supabase functions deploy` and the gateway's JWT check are proven only on a hosted project.

## Next steps

- [E-signatures and clickwrap with Supabase](https://esigncomply.com/supabase): how the pieces fit on this platform, with the things to watch for.
- [Clickwrap in Next.js and Supabase](https://esigncomply.com/guides/nextjs-supabase-clickwrap): Supabase with a Next.js server instead of Edge Functions, file by file.
- [AI app builders](https://esigncomply.com/docs/guides/ai-builders.md): where the key goes when a builder such as Lovable or Bolt generates the app.
- [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).
