# Record terms acceptance at sign-up with Better Auth

> Record terms acceptance at Better Auth sign-up. Two hooks confirm the sealed record with the esigncomply package before Better Auth writes the user row.

Source: https://esigncomply.com/docs/quickstart/better-auth

Last updated November 26, 2026

To record terms acceptance at Better Auth sign-up, create the session when the sign-up page loads, let the visitor tick the box and click, and send the record ID with Better Auth's own sign-up request. A hook confirms the record with the secret key before the user exists. 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 Better Auth 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/better-auth.md (the steps and the tested code for Better Auth)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Better Auth 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. Better Auth is the better-auth package, with the database the project already uses.
- No user exists when the sign-up page loads. The signer ID is a pending sign-up ID: a UUID the server makes, keeps in server-owned state with the pinned version IDs, and sets as an HttpOnly cookie. Never take the signer ID from anything else the browser sends.
- The sign-up route is Better Auth's own, POST /api/auth/sign-up/email. The page sends the record ID in a request header. Do not add a second sign-up route.
- Confirm in hooks.before (createAuthMiddleware, ctx.path === "/sign-up/email"): read the header with ctx.headers, the cookie with ctx.getCookie, and the record with esc.records.get. Never call Esign Comply from databaseHooks: the sign-up runs in a database transaction there.
- databaseHooks.user.create.before refuses a user row with no confirmed pending sign-up (throw APIError) and returns data with the signer ID, the record ID and the receipt. Declare the three columns in user.additionalFields with input: false.
- One record, one account: hand a confirmed pending sign-up out once.
- Server SDK calls return { data, error } and do not throw. Check error every time.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved. Keep the button disabled until the ceremony allows it, whatever the other fields hold.
- Expect live records only where ESIGNCOMPLY_LIVE is "true": production.

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 makes the pending sign-up ID, creates the session with esc.sessions.create and an Idempotency-Key, saves the ID and the pinned version IDs in server-owned state, sets the cookie, 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. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click, then the sign-up request with the record ID in its header.
6. Server: the request hook 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 does Better Auth create the user, with the record ID and the receipt on its 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:3000/signup --callback http://localhost:3000/api/auth/sign-up/email
  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. All of it runs on your machine. Better Auth is a library in your own server, so there is no account to create for it.

## 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 22 or later. The `esigncomply` package requires 20.19, and `better-sqlite3` 13.2.0 asks for 22. This page was run on Node.js 24.22.1.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Install Better Auth, a SQLite driver and the server package in a new folder. The page loads the browser SDK from a script tag, so there is nothing to bundle.

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
npm init -y && npm pkg set type=module
npm install better-auth better-sqlite3 esigncomply
mkdir public
```

`npm pkg set type=module` matters: `esigncomply` is an ES module, and Better Auth's documentation says CommonJS is not supported. `better-sqlite3` is the driver Better Auth's installation page shows first. With another database, keep the one your `auth` file already has.

## Step 2. Set the key

The secret key goes in `.env`, beside the two values Better Auth reads: its own secret and the base URL of your app. The file is never committed.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
BETTER_AUTH_SECRET=...
BETTER_AUTH_URL=http://localhost:3000
```

```bash
printf 'node_modules\n.env\n*.db\n*.db-*\n' > .gitignore
```

Better Auth's documentation asks for a secret of at least 32 characters with high entropy and suggests `openssl rand -base64 32`. For this page it was made with `node -e "console.log(require('node:crypto').randomBytes(32).toString('base64'))"`.

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
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}'
```

```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 `.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

No user exists when the sign-up page loads, so there is no user ID to name as the signer. The server makes a pending sign-up ID, a UUID, and that ID is the signer on the session and on the record. The [Signers API](https://esigncomply.com/docs/api/signers.md) describes this case: generate a UUID on your server, use it as the external ID, and store it on the account you create after confirmation.

One module holds the Esign Comply client and the pending sign-ups:

```js file="signups.js"
// signups.js
import { randomUUID } from "node:crypto";
import { EsignComply } from "esigncomply";

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

export 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";
// Seconds. The session, the cookie and the pending sign-up end together.
export const LIFETIME = 1800;

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

// No user exists when the page loads, so the signer is a pending sign-up: an ID this server makes and keeps.
export async function startSignup(pageUrl) {
  const signupId = randomUUID();
  const { data: session, error } = await esc.sessions.create(
    {
      profile: process.env.ESIGNCOMPLY_PROFILE_ID,
      // The form asks for no country or state, so they are fixed here. Take them from your form when it asks.
      signer: { external_id: signupId, class: "consumer", country: "US", region: "US-CA" },
      documents: [
        { document: DOCUMENTS.terms, version: "current" },
        { document: DOCUMENTS.privacy, version: "current" },
      ],
      context: { url: pageUrl, locale: "en-US", purpose: "account_signup" },
      expires_in: LIFETIME,
    },
    { idempotencyKey: `signup-${signupId}` },
  );
  if (error) return { error };
  for (const [id, signup] of pending) if (signup.expires < Date.now()) pending.delete(id);
  pending.set(signupId, { versions: session.documents.map((d) => d.version_id), expires: Date.now() + LIFETIME * 1000 });
  return { signupId, session };
}

// The record ID is the browser's claim. Read the record with the secret key and compare it with what this server holds.
export async function confirmSignup(signupId, recordId) {
  const signup = pending.get(signupId);
  if (!signup || typeof recordId !== "string") return null;
  const { data: record, error } = await esc.records.get(recordId);
  const confirmed =
    !error &&
    SEALED.includes(record.status) &&
    record.livemode === LIVE &&
    record.signer.external_id === signupId &&
    JSON.stringify(record.documents.map((d) => d.version_id).sort()) === JSON.stringify([...signup.versions].sort());
  if (!confirmed) return null;
  // From here on the record ID and the receipt are this server's own, not the browser's.
  signup.record = { id: record.id, receipt: record.receipt };
  return record;
}

// One record, one account: a confirmed sign-up is handed out once.
export function takeSignup(signupId) {
  const record = pending.get(signupId)?.record;
  if (record) pending.delete(signupId);
  return record;
}
```

The Map is enough for one process on your machine. In production keep the pending sign-ups in a table of your database, beside Better Auth's own tables: a Map is empty after a restart, and a second instance of the server does not see it.

Better Auth's instance goes in `auth.js`. The database is a SQLite file, e-mail and password sign-up is on, and three columns are added to Better Auth's `user` table. The two hooks are the subject of step 6.

```js file="auth.js"
// auth.js
import { betterAuth } from "better-auth";
import { APIError, createAuthMiddleware } from "better-auth/api";
import Database from "better-sqlite3";
import { confirmSignup, takeSignup } from "./signups.js";

const refuse = () =>
  new APIError("CONFLICT", {
    message: "We could not confirm whether your acceptance was recorded. Please wait while we check.",
  });

export const auth = betterAuth({
  database: new Database("./sqlite.db"),
  emailAndPassword: { enabled: true },
  user: {
    additionalFields: {
      // Server-owned columns: with input: false no request can set them. Only the database hook below does.
      esignSignerId: { type: "string", required: false, input: false },
      esignRecordId: { type: "string", required: false, input: false },
      esignReceipt: { type: "string", required: false, input: false, returned: false },
    },
  },
  hooks: {
    // Step 6: before the sign-up route runs, read the record the request names in its header, with the secret key.
    before: createAuthMiddleware(async (ctx) => {
      if (ctx.path !== "/sign-up/email") return;
      const record = await confirmSignup(ctx.getCookie("esc_signup"), ctx.headers?.get("x-esign-record"));
      console.log(record ? `confirmed ${record.id} (${record.status})` : "refused");
      if (!record) throw refuse();
    }),
  },
  databaseHooks: {
    user: {
      create: {
        // Before a user row is written, whichever route asked for it. No confirmed record, no user.
        before: async (user, ctx) => {
          const signupId = ctx?.getCookie("esc_signup");
          const record = takeSignup(signupId);
          if (!record) throw refuse();
          return { data: { ...user, esignSignerId: signupId, esignRecordId: record.id, esignReceipt: record.receipt } };
        },
      },
    },
  },
});
```

The server mounts Better Auth's handler under `/api/auth` and creates the session in `POST /api/ceremony`. It returns three values to the browser: the client token, the API URL and the pinned documents.

```js file="server.js"
// server.js
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { toNodeHandler } from "better-auth/node";
import { auth } from "./auth.js";
import { DOCUMENTS, LIFETIME, esc, startSignup } from "./signups.js";

// Better Auth's own handler: sign-up, sign-in, the session and the rest, under /api/auth.
const authHandler = toNodeHandler(auth);
const SECURE = (process.env.BETTER_AUTH_URL ?? "").startsWith("https://") ? "; Secure" : "";

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

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

  if (url.pathname.startsWith("/api/auth/")) return authHandler(req, res);

  if (req.method === "GET" && url.pathname === "/signup") {
    res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    return res.end(await readFile(new URL("./public/signup.html", import.meta.url)));
  }

  // 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") {
    // The page that runs the ceremony: the origin the browser reports, plus its path.
    const { signupId, session, error } = await startSignup(`${req.headers.origin ?? url.origin}/signup`);
    if (error) return json(res, 502, { error: error.code });
    // The pending sign-up ID goes back as a cookie the page's script cannot read. Better Auth's routes receive it.
    const cookie = `esc_signup=${signupId}; HttpOnly; SameSite=Lax; Path=/api/auth; Max-Age=${LIFETIME}${SECURE}`;
    return json(res, 200, { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents }, { "Set-Cookie": cookie });
  }

  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 ?? 3000);
server.listen(port, () => console.log(`http://localhost:${port}/signup`));
```

The route sets the pending sign-up ID as an `HttpOnly` cookie for `/api/auth`. The page's script cannot read it, and the browser sends it with the sign-up request.

Every route runs inside `handle`, and the server answers `500` when one throws. In the test a request for `//`, which makes `new URL` throw, was answered `500`, the sign-up page still answered `200`, and the process kept running.

Create Better Auth's tables, then start the server:

```bash
npx auth@latest migrate --config ./auth.js --yes
node --env-file=.env server.js
```

```text
-> name, email, emailVerified, image, createdAt, updatedAt, esignSignerId, esignRecordId, esignReceipt fields on user table.
http://localhost:3000/signup
```

The first line is from the migration, which also lists the `session`, `account` and `verification` tables. The three `esign` columns come from `user.additionalFields`.

## 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`: the server sends it at `/signup`, so the page, the document pages, your route and Better Auth's routes share one origin.

```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; }
      label { display: block; margin: 0 0 12px; }
      input:not([type="checkbox"]) { display: block; width: 100%; box-sizing: border-box; font: inherit; padding: 8px; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <label>Name <input name="name" autocomplete="name" required /></label>
      <label>Email <input name="email" type="email" autocomplete="email" required /></label>
      <label>Password <input name="password" type="password" autocomplete="new-password" minlength="8" required /></label>
      <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 form = document.querySelector("#signup");
      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 });
      // The button opens when the ceremony allows it. The browser checks the three fields when it is clicked.
      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.

      let sent = false; // one sign-up request at a time, and none once the account exists
      form.addEventListener("submit", async (event) => {
        event.preventDefault();
        if (sent) return;
        sent = true;
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // Better Auth's sign-up route, with the record ID in a header. The server confirms the record before the user exists.
          const signedUp = await fetch("/api/auth/sign-up/email", {
            method: "POST",
            headers: { "Content-Type": "application/json", "X-Esign-Record": result.recordId },
            body: JSON.stringify(Object.fromEntries(new FormData(form))), // name, email, password
          });
          if (signedUp.ok) return (message.textContent = `Account created. Record ${result.recordId}`);
          message.textContent = (await signedUp.json()).message;
        } catch (error) {
          message.textContent = error.message;
        }
        sent = false; // refused: the visitor corrects the form and clicks again. complete() returns the same record.
      });
    </script>
  </body>
</html>
```

Open [http://localhost:3000/signup](http://localhost:3000/signup). 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. Fill in the three fields. The button stays disabled until the box is ticked, whatever the fields hold: the ceremony decides when it opens, and the browser checks the fields when it is clicked. Tick the box, click **Create account**, and the page shows:

```text
Account created. Record rec_d6g5VvVocHRWR6Ekc9qf
```

One page load sent one `POST /api/ceremony`. In the test a second click after that message sent no request.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. The page sends the record ID in the `X-Esign-Record` header of Better Auth's own sign-up request, and two hooks in `auth.js` stand between that request and a user row.

`hooks.before` runs before the sign-up route. It reads the record with the secret key and lets the request through only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the pending sign-up the cookie names; and the document versions are exactly the ones the session pinned. Otherwise it answers `409`. This step is never optional.

`databaseHooks.user.create.before` runs before Better Auth writes a user row, whichever route asked for it. It refuses a row that has no confirmed pending sign-up, and it writes the pending sign-up ID, the record ID and the receipt into the row. The three columns are declared with `input: false`, so no request can set them.

The call to Esign Comply is in the request hook for a reason the test showed. With better-auth 1.7.28 and better-sqlite3 13.2.0, a database hook that waited 2 seconds held a sign-in sent at the same moment for 2.1 seconds. The same wait in `hooks.before` held nothing. So the database hook reads the Map and calls nothing.

`ESIGNCOMPLY_LIVE` is `true` in production only, the one environment that holds the live key. Everywhere else it is not set, so test records are accepted and live records are not.

The server logs one line for each confirmation:

```text
confirmed rec_d6g5VvVocHRWR6Ekc9qf (recorded)
```

The session Better Auth returns for the new user carries `esignSignerId` and `esignRecordId`. The receipt stays on the server: its column is declared with `returned: false`.

A sign-up with no record creates no user:

```bash
curl -s -X POST http://localhost:3000/api/auth/sign-up/email \
  -H "Content-Type: application/json" -H "Origin: http://localhost:3000" \
  -d '{"name":"Dana Whitfield","email":"dana@example.org","password":"correct-horse-9"}'
```

```json
{"message":"We could not confirm whether your acceptance was recorded. Please wait while we check."}
```

In the test the same answer, with status `409`, came back for a made-up record ID, for a real sealed record of another sign-up, for a second sign-up with a record already used, and for Better Auth's server API called with no request behind it. The `user` table did not change. A call to Better Auth's `update-user` route that named `esignRecordId` was answered `400`.

One record, one account. In the test four sign-ups were sent at once with one record and four e-mail addresses. The server logged four `confirmed` lines, one request was answered `200`, three were answered `409`, and one user row was written.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs the hook 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:3000/signup --callback http://localhost:3000/api/auth/sign-up/email
```

Here the callback is Better Auth's sign-up route, because that is where the record is confirmed. The check fills the empty name, e-mail and password fields with test values of its own before it ticks the box.

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:3000/api/auth/sign-up/email answered 409.

Ceremonies
  390x844    record rec_GtFomJmxovYX6HJetgef  session ses_4KdPEW28pnX0G6Sbjw9d, 5 events
  768x1024   record rec_FH4LcP2FMNkS2t7pQ2e3  session ses_3bnFqk6GCEUQucy4UZKP, 5 events
  1440x900   record rec_K4QDxDCp8CvAtK4W6K8K  session ses_5EcnAEP6qnKVForXmJp4, 5 events

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

The server logged a `confirmed` line for each of the three records, and the `user` table held three new rows named `Conformance Check`, each with its own record ID. They are real rows in your development database: delete them when you are done.

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 look at Better Auth's own settings. The statements below are from Better Auth's documentation, read on November 26, 2026: [Introduction](https://better-auth.com/docs/introduction), [Installation](https://better-auth.com/docs/installation), [Hooks](https://better-auth.com/docs/concepts/hooks), [Database](https://better-auth.com/docs/concepts/database), [API](https://better-auth.com/docs/concepts/api), [CLI](https://better-auth.com/docs/concepts/cli), [Rate Limit](https://better-auth.com/docs/concepts/rate-limit), [Cookies](https://better-auth.com/docs/concepts/cookies), [Email & Password](https://better-auth.com/docs/authentication/email-password), [SQLite](https://better-auth.com/docs/adapters/sqlite), [Express Integration](https://better-auth.com/docs/integrations/express) and [Options](https://better-auth.com/docs/reference/options). Nothing on this page was deployed.

**The secret and the base URL.** Set `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` where your host keeps secrets, beside `ESIGNCOMPLY_API_KEY`. Better Auth's documentation says it throws in production when no secret is set, and that you should always set the base URL and not rely on the incoming request. The cookie this page sets gets `Secure` when `BETTER_AUTH_URL` starts with `https://`. Better Auth's documentation says its own cookies are `httpOnly` and `secure` when the server runs in production mode.

**The database.** Run `npx auth@latest migrate` in the release step of your host. Better Auth's documentation says the command is for its built-in Kysely adapter, which covers SQLite, PostgreSQL and MySQL, and that with Prisma or Drizzle you generate the schema and migrate with your ORM. This page was run with SQLite only.

**The install on your host.** On the test machine, which has no `make`, `npm ci` with the lock file ran `node-gyp rebuild` for `better-sqlite3` 13.2.0 and failed. `npm ci --ignore-scripts` installed, and the driver loaded from the prebuilt binary the package ships.

**The rate limiter.** Better Auth's documentation says its rate limiter is off in development and on in production, with 100 requests in 10 seconds by default and stricter rules for some paths, and that it reads the client address from `X-Forwarded-For` unless you set `advanced.ipAddress`. In the test with `NODE_ENV=production` the fourth sign-up within 10 seconds was answered `429` with `x-retry-after: 10`. With no proxy in front, Better Auth logged that it could not determine a client IP and was using one shared bucket for the path. Set the address header for your host before you go live.

**Several instances.** Move the pending sign-ups from the Map to a table. The request that creates the session and the request that signs up can reach different instances.

**E-mail verification.** Better Auth's documentation says that with `requireEmailVerification` on, or `autoSignIn` off, the sign-up route answers `200` whether the e-mail is already registered or not. This page was run with neither. With one of them, a `200` no longer tells the page that a user was created.

**Previews and test mode.** A preview keeps the test key and needs `BETTER_AUTH_URL` set to its own address. A test key refuses a host it does not know with [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch). List the exact host under Domains in the dashboard, or with the API:

```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": ["preview.example.dev"] }'
```

List exact hosts, up to 25, and take a host off the list when its preview is gone.

**The production domain.** Register the domain your server serves the sign-up page on, and verify it with one DNS record. 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`.** The server was started without `--env-file=.env`, so the SDK found no key. In a test the server started with an empty key and the route answered `502` with this code, while the page still answered `200`. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`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 or a tunnel. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch) and [Test mode](https://esigncomply.com/docs/guides/test-mode.md).
- **`429` when the hook reads the record.** The hook needs no retry loop: the `esigncomply` package waits for the time in `Retry-After` and tries again, up to twice. In the test, four sign-ups sent at once with one record gave four `confirmed` lines, two of the answers a second later than the others. 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).
- **`Too many requests. Please try again later.` on the page.** That `429` is Better Auth's own rate limiter, not Esign Comply. The record is already sealed. The page shows Better Auth's message, and a later click sends the same record ID, as it did in the test when Better Auth refused a taken e-mail. See the rate limiter note in step 8.

## Questions about the Better Auth quickstart

### Who is the signer when no user exists yet?

A pending sign-up. The server makes a UUID when the page loads, names it as the signer on the session, and keeps it with the pinned versions. After confirmation the database hook writes that ID to the `esignSignerId` column of the new user, so the record and the account name each other.

### Why is the record confirmed in a request hook and not in the database hook?

Because a database hook that waits holds other queries up. In the test with better-auth 1.7.28 and better-sqlite3 13.2.0, a database hook that waited 2 seconds delayed a sign-in sent at the same moment by 2 seconds. The same wait in the request hook delayed nothing. The database hook on this page calls no service.

### What happens when Better Auth refuses the sign-up after the record is sealed?

The record stays with the pending sign-up, and the next click sends it again. In the test Better Auth answered `422` twice for an e-mail that was taken, and the page sent the same record ID both times. A sign-up request with that record and a free address then created the account. Show Better Auth's message and let the visitor correct the form.

### Can a signed-in user change the record ID on their row?

Not through Better Auth's routes. The three columns are declared with `input: false`. In the test a call to the `update-user` route that named `esignRecordId` was answered `400` with the message that the field is not allowed to be set.

### Does the conformance check fill in the sign-up form?

Yes. It fills empty visible e-mail, password, phone and text fields with test values of its own before it ticks the box. In the test it signed up three users named `Conformance Check`, each with its own address at `example.com` and its own record.

### Was this quickstart run on a deployed server?

Not yet. It ran on one machine, as one Node.js server with a SQLite file, against the API in test mode. Other databases, e-mail verification, social sign-in, several instances and a host behind a proxy are proven only when you run them.

## Next steps

- [Record terms acceptance at Better Auth sign-up](https://esigncomply.com/better-auth): how the pieces fit with Better Auth's hooks, with the things to watch for.
- [Signers API](https://esigncomply.com/docs/api/signers.md): the external ID, and what you can read for a signer later.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Register a domain](https://esigncomply.com/docs/guides/domains.md): DNS and file verification, statuses, and test origins.
- [Add e-signatures and clickwrap with Node.js](https://esigncomply.com/docs/quickstart/nodejs.md): the same server without a sign-up form.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
