# Record terms acceptance at Better Auth sign-up

> Record terms acceptance at Better Auth sign-up: a request hook reads the record with the esigncomply package, and a database hook stores the receipt.

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

Platform · Better Auth

To record terms acceptance at Better Auth sign-up, create a session for a pending sign-up ID when the page loads and send the record ID with Better Auth's own sign-up request. A request hook confirms it with the secret key, and a database hook stores the receipt on the user row. Esign Comply seals each acceptance as an independent record.

Follow the quickstart and each signature is a valid electronic signature under the U.S. ESIGN Act, state UETA laws and New York's ESRA, and each clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/better-auth)

`npm install better-auth better-sqlite3 esigncomply`

[Better Auth quickstart](https://esigncomply.com/docs/quickstart/better-auth)

Free plan: 10 live signatures a month and a full test mode. No card required.

Last updated November 26, 2026

Run locally for Better Auth before publishing

**Better Auth hooks**

auth.js (excerpt)

```js
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 } };
        },
      },
    },
  },
});
```

**Session route**

server.js (excerpt)

```js
// 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 });
}
```

**Pending sign-up**

signups.js (excerpt)

```js
// 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;
}
```

**Sign-up request**

public/signup.html (excerpt)

```html
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.
});
```

Integrate with Better Auth

## How do you integrate Esign Comply with Better Auth?

With Better Auth the sign-up route is the library's own, so no second route confirms the record. The page sends the record ID in a header of `POST /api/auth/sign-up/email`, a request hook reads the record with the secret key, and a database hook writes the receipt to the `user` row. No user exists when the page loads, so the signer is a pending sign-up ID your server makes. The record is at level L1: your app asserts who the signer is.

Better Auth is a framework-agnostic, universal authentication and authorization framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities.

Source: [Better Auth documentation, Introduction](https://better-auth.com/docs/introduction), read on November 26, 2026.

[Better Auth quickstart](https://esigncomply.com/docs/quickstart/better-auth) · [All platforms](https://esigncomply.com/platforms)

Where each part lives on Better Auth

- **Better Auth hooks** · `auth.js`
- **Session route** · `server.js`
- **Pending sign-up** · `signups.js`
- **Sign-up request** · `public/signup.html`

Run on 2026-11-26 with Node.js 24.22.1, better-auth 1.7.28, better-sqlite3 13.2.0, esigncomply 1.0.4, the browser SDK script build and the conformance check from esigncomply 1.0.4, as one Node.js server with a SQLite file and no account anywhere, against the API in test mode. Better Auth's rate limiter was seen with NODE_ENV=production on the same machine. The four sign-ups sent at once with one record were run while the record ID still travelled in the request body, before it moved to a header. The check and the typed sign-up were run after. The settings in step 8 are from Better Auth's documentation as of that date. Nothing was deployed, and e-mail verification, social sign-in, other databases and several instances were not run.

Three steps

## How does Esign Comply fit with Better Auth?

Each step uses a feature Better Auth already has. The secret key stays on the server side of Better Auth in all three.

1. **A route of yours creates the session**

   `POST /api/ceremony` sits beside Better Auth's handler, which `toNodeHandler` mounts under `/api/auth`. The route makes a pending sign-up ID, names it as the signer, keeps the pinned versions, and sets the ID as an `HttpOnly` cookie for Better Auth's routes. Source: [Better Auth documentation, Installation](https://better-auth.com/docs/installation), read on November 26, 2026.

2. **A request hook confirms the record**

   `hooks.before`, written with `createAuthMiddleware`, runs before `/sign-up/email`. It reads the record ID from a header through `ctx.headers`, the cookie through `ctx.getCookie`, and the record with the secret key. A record that does not match is answered `409` with an `APIError`. Source: [Better Auth documentation, Hooks](https://better-auth.com/docs/concepts/hooks), read on November 26, 2026.

3. **A database hook writes the receipt**

   `databaseHooks.user.create.before` runs before any user row is written. It refuses a row with no confirmed pending sign-up and returns the row with three more columns, declared in `user.additionalFields` with `input: false`: the pending sign-up ID, the record ID and the receipt. Source: [Better Auth documentation, Database](https://better-auth.com/docs/concepts/database), read on November 26, 2026.

Better Auth setup

## Where do the key, the preview hosts and the webhook go on Better Auth?

Four settings carry an Esign Comply integration on Better Auth. What is said here about Better Auth was read from its own documentation, and the quickstart has each command.

### The secret and the base URL

`BETTER_AUTH_SECRET` and `BETTER_AUTH_URL` sit beside `ESIGNCOMPLY_API_KEY` where your host keeps secrets. Better Auth's documentation asks for a secret of at least 32 characters, says it throws in production when none is set, and says to set the base URL and not rely on the incoming request.

Source: [Better Auth documentation, Options](https://better-auth.com/docs/reference/options), read on November 26, 2026.

### The tables and the three columns

`npx auth@latest migrate` creates Better Auth's tables. In the test it listed `esignSignerId`, `esignRecordId` and `esignReceipt` among the fields of the `user` table. Better Auth's documentation says the command is for its built-in Kysely adapter, and that with Prisma or Drizzle you generate the schema and migrate with your ORM.

Source: [Better Auth documentation, CLI](https://better-auth.com/docs/concepts/cli), read on November 26, 2026.

### Preview hosts and test mode

A preview keeps the test key and gets its own `BETTER_AUTH_URL`: Better Auth's documentation says it trusts the base URL of your app by default. A test key refuses a host it does not know, so list the preview's exact host under Domains in the Esign Comply dashboard as a test origin.

Source: [Better Auth documentation, Options](https://better-auth.com/docs/reference/options), read on November 26, 2026.

### The registered domain and the webhook

Register the domain your server serves the sign-up page on, and verify it with one DNS record. For the `record.completed` webhook, add a route to the server beside Better Auth's handler and register its production URL under Webhooks in the Esign Comply dashboard.

Read on November 26, 2026: [Better Auth documentation, Introduction](https://better-auth.com/docs/introduction), [Better Auth documentation, Installation](https://better-auth.com/docs/installation), [Better Auth documentation, Hooks](https://better-auth.com/docs/concepts/hooks), [Better Auth documentation, Database](https://better-auth.com/docs/concepts/database), [Better Auth documentation, API](https://better-auth.com/docs/concepts/api), [Better Auth documentation, CLI](https://better-auth.com/docs/concepts/cli), [Better Auth documentation, Rate Limit](https://better-auth.com/docs/concepts/rate-limit), [Better Auth documentation, Cookies](https://better-auth.com/docs/concepts/cookies), [Better Auth documentation, Email & Password](https://better-auth.com/docs/authentication/email-password), [Better Auth documentation, SQLite](https://better-auth.com/docs/adapters/sqlite), [Better Auth documentation, Express Integration](https://better-auth.com/docs/integrations/express), [Better Auth documentation, Options](https://better-auth.com/docs/reference/options).

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a Better Auth app?

Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes on Better Auth, what to build and what never to do, and it ends with the rules block for your project.

The rules block lives at [/rules.md](https://esigncomply.com/rules.md). Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version, with your own document and profile IDs.

[Pages for each AI tool](https://esigncomply.com/build)

Prompt: Esign Comply clickwrap on Better Auth

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

3 things to watch

## What goes wrong when you add e-signatures on Better Auth?

These are specific to Better Auth. Each one was seen while the quickstart's code was run, or is in Better Auth's own documentation.

- **A database hook that waits holds every other query**

  In the test with better-auth 1.7.28 and better-sqlite3 13.2.0, a `databaseHooks.user.create.before` 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. The quickstart reads the record in the request hook, and its database hook calls no service.

- **The fourth sign-up in 10 seconds gets 429 from Better Auth**

  Better Auth's documentation says its rate limiter is on in production and off in development. In the test with `NODE_ENV=production`, the fourth sign-up within 10 seconds was answered `429` with `x-retry-after: 10`, and with no proxy in front Better Auth logged that it used one shared bucket for the path. Set the client address header for your host before you go live.

  Source: [Better Auth documentation, Rate Limit](https://better-auth.com/docs/concepts/rate-limit), read on November 26, 2026.

- **npm ci rebuilt better-sqlite3 where the first install had not**

  On the test machine, which has no `make`, the first `npm install` added `better-sqlite3` 13.2.0 and the driver loaded. With the lock file in place, `npm ci` ran `node-gyp rebuild` for it and failed. `npm ci --ignore-scripts` installed, and the driver loaded from the prebuilt binary the package ships. Check the install command of your host's build.

## Where are the Better Auth quickstart and the API reference?

Start with the quickstart: it carries every file this page excerpts, in the order you write them.

- Quickstart

  **[Better Auth quickstart](https://esigncomply.com/docs/quickstart/better-auth)**

  Step by step, from install to your first sealed test record, with every file and the output of each step.

- Reference

  **[API reference](https://esigncomply.com/docs/api)**

  Every endpoint, field and error code. Sessions, records and documents are the three this page uses.

- Guide

  **[Server confirmation](https://esigncomply.com/docs/guides/server-confirmation)**

  The one place access is granted: what to compare, and the webhook that backs the check up.

Verifiable

## What does Esign Comply record for a signature on Better Auth?

The same record on every stack and platform. Your Better Auth code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on [Evidence and verification](https://esigncomply.com/product/evidence).

- **Observed and asserted fields**

  Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.

- **A signed receipt**

  `complete()` returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, and `GET /v1/records/{id}/receipt` returns it again.

- **An external timestamp**

  An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.

- **An offline verifier**

  Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source `esigncomply-verify`, without an account.

[How sealing and verification work](https://esigncomply.com/product/evidence) · [Observed and asserted, in the docs](https://esigncomply.com/docs/concepts/observed-and-asserted) · [The offline verifier](https://esigncomply.com/docs/sdk/verify)

Record

`rec_Z4m8`

simple · L1

Recorded

Written durably, receipt signed with ES256

Timestamped

External RFC 3161 token over the record hash

Anchored

Public anchor pending

Checkbox changed by a trusted user event · observed

Terms of Service, version dv_3kT9 · observed

Server time 2026-11-21T15:03:20.291Z · observed

Signer email dana@example.org · asserted

record_hash sha256:5be7… · example record

## Questions about e-signatures on Better Auth

### How does test mode work on a Better Auth sign-up page?

A test key works on `localhost` with no setup, which is where this page's code ran: one Node.js server, a SQLite file, nothing deployed. A preview runs on another host, which a test key refuses until you list that exact host under Domains as a test origin. Give the preview its own `BETTER_AUTH_URL` as well.

### Where should the receipt be stored with Better Auth?

On the `user` row. The quickstart adds three columns through `user.additionalFields`, all with `input: false`: the pending sign-up ID, the record ID and the receipt. The database hook writes them when the user is created. Esign Comply keeps the sealed record itself, and the receipt is the signed token that names it.

### Who is the signer before the Better Auth user exists?

A pending sign-up ID, a UUID your server makes when the page loads. It is the signer on the session and on the record, and after confirmation it is written to the new user's row. This is level L1: your app asserts who the signer is, and the row ties the ID to the e-mail address the visitor typed.

### Why does the page use two Better Auth hooks?

Because each does one job at the right moment. The request hook reads the record with the secret key before the sign-up route runs. The database hook refuses any user row without a confirmed pending sign-up and writes the receipt. In the test a database hook that waited held other queries up, so the network call is not there.

### What if 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 a taken e-mail, and the page sent the same record ID both times. A sign-up with that record and a free address then created the account. One record creates one account at most.

### Other platforms

- [Supabase](https://esigncomply.com/supabase)
- [Turso](https://esigncomply.com/turso)
- [PocketBase](https://esigncomply.com/pocketbase)

### Stacks used with Better Auth

- [Node.js](https://esigncomply.com/nodejs)
- [Express](https://esigncomply.com/express)
- [Next.js](https://esigncomply.com/nextjs)

[All platforms](https://esigncomply.com/platforms) · [All stacks](https://esigncomply.com/stacks) · [Clickwrap API](https://esigncomply.com/clickwrap) · [E-signature API](https://esigncomply.com/sign)

## Better Auth creates the user. The record proves what they accepted.

[Get an API key](https://esigncomply.com/signup) · [Read the docs](https://esigncomply.com/docs/quickstart/better-auth)

Free plan: 10 live signatures a month and a full test mode. No card required.

Better Auth is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about Better Auth is from Better Auth's documentation or from a test run, as marked, on November 26, 2026. `/better-auth.md` is this page as Markdown.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.

---

Esign Comply is the e-signature API and clickwrap API for developers who build their own signing flow in their own UI: it supplies the ceremony rules as a generated prompt for AI coding tools, records events in direct browser ceremonies, and seals independent, verifiable evidence.
