# E-signatures and clickwrap with PocketBase

> E-signatures and clickwrap with PocketBase: pb_hooks routes call the REST API with $http.send, and a collection with locked API rules keeps the receipt.

Source: https://esigncomply.com/pocketbase

Platform · PocketBase

To add e-signatures and clickwrap with PocketBase, extend the one binary with JavaScript in `pb_hooks`. Two routes call the REST API with PocketBase's own `$http.send`, and the secret key stays in the environment of the process. A collection with locked API rules keeps the pinned versions and the receipt. 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/pocketbase)

No package to install: the hooks call the REST API with $http.send

[PocketBase quickstart](https://esigncomply.com/docs/quickstart/pocketbase)

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

Last updated November 26, 2026

Run locally for PocketBase before publishing

**Session route**

pb_hooks/main.pb.js (excerpt)

```js
// Step 4: create the session with the secret key. The browser gets the client token only.
routerAdd("POST", "/api/ceremony", (e) => {
  const esc = require(`${__hooks}/esc.js`);
  // The page that runs the ceremony: the origin the browser reports, plus its path.
  const origin = e.request.header.get("Origin") || "http://" + e.request.host;
  const res = esc.call(
    "POST",
    "/sessions",
    {
      profile: $os.getenv("ESIGNCOMPLY_PROFILE_ID"),
      signer: esc.signer,
      documents: [
        { document: esc.documents.terms, version: "current" },
        { document: esc.documents.privacy, version: "current" },
      ],
      context: { url: origin + "/signup", locale: "en-US", purpose: "account_signup" },
    },
    "signup-" + esc.signer.external_id + "-" + $security.randomString(24),
  );
  if (res.status !== 201) return e.json(502, { error: res.data.error.code });

  // One row per signer, in a collection whose API rules are locked: only the hooks and a superuser read it.
  const collection = e.app.findCollectionByNameOrId("esc_acceptances");
  let row;
  try {
    row = e.app.findFirstRecordByData("esc_acceptances", "signer_id", esc.signer.external_id);
  } catch (_) {
    row = new Record(collection);
    row.set("signer_id", esc.signer.external_id);
  }
  row.set("version_ids", res.data.documents.map((d) => d.version_id).sort());
  e.app.save(row);
  return e.json(200, { clientToken: res.data.client_token, apiUrl: res.data.api_url, documents: res.data.documents });
});
```

**REST helper**

`pb_hooks/esc.js`

```js
// pb_hooks/esc.js: what the routes share. A handler cannot see variables of main.pb.js, so each one loads this with require().
// There is no Esign Comply package for the hooks: the REST API is called with PocketBase's own HTTP helper.
const API = $os.getenv("ESIGNCOMPLY_API_URL") || "https://esigncomply.com/v1";

module.exports = {
  // The signer. In your app this is the signed-in user, or the account you are about to create.
  signer: {
    external_id: "user_7c1d",
    email: "dana@example.org",
    name: "Dana Whitfield",
    class: "consumer",
    country: "US",
    region: "US-CA",
  },
  documents: {
    terms: $os.getenv("ESIGNCOMPLY_TERMS_ID"),
    privacy: $os.getenv("ESIGNCOMPLY_PRIVACY_ID"),
  },
  sealed: ["recorded", "timestamped", "anchored"],
  // "true" in production only. Every other instance holds the test key and leaves it unset.
  live: $os.getenv("ESIGNCOMPLY_LIVE") === "true",

  // One call to the REST API with the secret key, which stays in the environment of the PocketBase process.
  // $http.send waits for the whole response and throws on a timeout or a network error.
  call: function (method, path, body, idempotencyKey) {
    const headers = { Authorization: "Bearer " + $os.getenv("ESIGNCOMPLY_API_KEY"), "Content-Type": "application/json" };
    if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
    const request = { url: API + path, method: method, headers: headers, body: body ? JSON.stringify(body) : "", timeout: 15 };
    let res = $http.send(request);
    // Nothing retries for you here. On 429 wait for the seconds in Retry-After, 1 at least and 5 at most,
    // and send the same request again, twice at most. Nothing else is retried.
    for (let attempt = 1; res.statusCode === 429 && attempt < 3; attempt++) {
      const wait = res.headers["Retry-After"] ? Number(res.headers["Retry-After"][0]) : 1;
      sleep(1000 * Math.min(Math.max(wait || 1, 1), 5));
      res = $http.send(request);
    }
    return { status: res.statusCode, data: res.json };
  },
};
```

**Confirm**

pb_hooks/main.pb.js (excerpt)

```js
// Step 6: confirm the record with the secret key before the account exists.
routerAdd("POST", "/api/signup/confirm", (e) => {
  const esc = require(`${__hooks}/esc.js`);
  const recordId = String(e.requestInfo().body.recordId || "missing");
  const res = esc.call("GET", "/records/" + encodeURIComponent(recordId));
  const record = res.data;

  let row = null;
  let expected = [];
  try {
    row = e.app.findFirstRecordByData("esc_acceptances", "signer_id", esc.signer.external_id);
    // get() on a json field returns the bytes of the JSON text, so read it as a string and parse it.
    expected = JSON.parse(row.getString("version_ids"));
  } catch (_) {}

  const confirmed =
    res.status === 200 &&
    esc.sealed.indexOf(record.status) >= 0 &&
    record.livemode === esc.live &&
    record.signer.external_id === esc.signer.external_id &&
    expected.length > 0 &&
    JSON.stringify(record.documents.map((d) => d.version_id).sort()) === JSON.stringify(expected);
  console.log(confirmed ? "confirmed " + record.id + " (" + record.status + ")" : "refused");
  if (!confirmed) return e.json(409, { confirmed: false });

  // Only now create the account. The record ID and the receipt go in the same row.
  row.set("record_id", record.id);
  row.set("receipt", record.receipt);
  row.set("confirmed_at", new DateTime());
  e.app.save(row);
  return e.json(200, { confirmed: true, recordId: record.id });
});
```

**Collection**

`pb_migrations/1795000000_create_esc_acceptances.js`

```js
// pb_migrations/1795000000_create_esc_acceptances.js: applied once, when PocketBase starts.
migrate(
  (app) => {
    const collection = new Collection({
      type: "base",
      name: "esc_acceptances",
      // All five API rules are null, which PocketBase calls locked: the Web API answers only a superuser.
      // The hooks do not go through the Web API, so they read and write the collection all the same.
      listRule: null,
      viewRule: null,
      createRule: null,
      updateRule: null,
      deleteRule: null,
      fields: [
        { name: "signer_id", type: "text", required: true },
        { name: "version_ids", type: "json", required: true },
        { name: "record_id", type: "text" },
        { name: "receipt", type: "text" },
        { name: "confirmed_at", type: "date" },
      ],
      indexes: ["CREATE UNIQUE INDEX idx_esc_acceptances_signer ON esc_acceptances (signer_id)"],
    });
    app.save(collection);
  },
  (app) => {
    app.delete(app.findCollectionByNameOrId("esc_acceptances"));
  },
);
```

Integrate with PocketBase

## How do you integrate Esign Comply with PocketBase?

With PocketBase the server half is JavaScript in `pb_hooks`, run by the binary's embedded engine and not by Node.js. Each handler runs in a scope of its own, so the routes load what they share with `require()`. They call the REST API with `$http.send`, read the key with `$os.getenv`, and keep the pinned versions in a collection that a migration creates with every API rule locked.

PocketBase is an open source backend consisting of embedded database (SQLite) with realtime subscriptions, builtin auth management, convenient dashboard UI and simple REST-ish API.

Source: [PocketBase documentation, Introduction](https://pocketbase.io/docs/), read on November 26, 2026.

[PocketBase quickstart](https://esigncomply.com/docs/quickstart/pocketbase) · [All platforms](https://esigncomply.com/platforms)

Where each part lives on PocketBase

- **Session route** · `pb_hooks/main.pb.js`
- **REST helper** · `pb_hooks/esc.js`
- **Confirm** · `pb_hooks/main.pb.js`
- **Collection** · `pb_migrations/1795000000_create_esc_acceptances.js`

Run on 2026-11-26 with the prebuilt PocketBase 0.42.3 executable for Linux x64, started with --dir, --hooksDir, --migrationsDir and --publicDir pointing at the folders of this project, with no Node.js and no package in the project, and with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode. A second instance with a data folder of its own was tried, the collection was read as a superuser, as a signed-in user and as a guest, and the JavaScript engine of the hooks was probed in the same version. Everything ran on one machine over plain HTTP on localhost. TLS, a domain, a reverse proxy, backups and updates of PocketBase are from its documentation as of that date and were not run.

Three steps

## How does Esign Comply fit with PocketBase?

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

1. **The environment of the binary holds the key**

   The hooks read `ESIGNCOMPLY_API_KEY` with `$os.getenv`. PocketBase loads no `.env` file: in the test an instance started beside one, without loading it, answered `missing_api_key`. Load the file into the shell that starts PocketBase, or set the variable in its service.

2. **A hook route creates the session**

   `routerAdd("POST", "/api/ceremony", ...)` sends `POST /v1/sessions` with `$http.send` and returns the client token. PocketBase serves the signup page from `pb_public`, and the browser SDK records the ceremony from the signer's device. Source: [PocketBase documentation, Routing](https://pocketbase.io/docs/js-routing/), read on November 26, 2026.

3. **A locked collection keeps the receipt**

   A migration creates `esc_acceptances` with all five API rules `null`. PocketBase's documentation calls that locked: only a superuser can perform the action through the Web API. The confirm route reads the record with the secret key, compares it with the row, and writes the record ID and the receipt into it. Source: [PocketBase documentation, API rules and filters](https://pocketbase.io/docs/api-rules-and-filters/), read on November 26, 2026.

PocketBase setup

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

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

### The key and the other variables

Set `ESIGNCOMPLY_API_KEY`, the three IDs and, in production only, `ESIGNCOMPLY_LIVE=true` in the environment of the PocketBase process. The production guide runs PocketBase as a systemd service: the variables belong to that service. Never put the key in `pb_public`, which is served to everyone, or in `pb_migrations`, which is committed.

Source: [PocketBase documentation, Going to production](https://pocketbase.io/docs/going-to-production/), read on November 26, 2026.

### Routes and static files

The hooks own `/signup`, `/legal/{slug}`, `/api/ceremony` and `/api/signup/confirm`, and all of them answered in the test. PocketBase serves `pb_public/signup.html` at `/signup.html`, so one route serves the same file at `/signup`. PocketBase's documentation suggests a prefix such as `/api/myapp/` for your own routes, to avoid collisions with system routes.

Source: [PocketBase documentation, Routing](https://pocketbase.io/docs/js-routing/), read on November 26, 2026.

### Preview instances and test mode

PocketBase's FAQ says it is self-hosted only, so a preview is another PocketBase process on another host, with a `pb_data` folder of its own and the test key. List that exact host under Domains in the Esign Comply dashboard as a test origin. On `localhost` a test key works with no setup.

Source: [PocketBase, FAQ](https://pocketbase.io/faq/), read on November 26, 2026.

### The registered domain and the webhook

The production guide starts PocketBase with `./pocketbase serve yourdomain.com`, which issues a Let's Encrypt certificate for the domain. Register the same domain with Esign Comply and verify it with one DNS record. For the `record.completed` webhook, add one more `routerAdd` route and register its production URL under Webhooks in the Esign Comply dashboard.

Source: [PocketBase documentation, Going to production](https://pocketbase.io/docs/going-to-production/), read on November 26, 2026.

Read on November 26, 2026: [PocketBase documentation, Introduction](https://pocketbase.io/docs/), [PocketBase documentation, Extend with JavaScript](https://pocketbase.io/docs/js-overview/), [PocketBase documentation, Routing](https://pocketbase.io/docs/js-routing/), [PocketBase documentation, Sending HTTP requests](https://pocketbase.io/docs/js-sending-http-requests/), [PocketBase documentation, Migrations](https://pocketbase.io/docs/js-migrations/), [PocketBase documentation, Collection operations](https://pocketbase.io/docs/js-collections/), [PocketBase documentation, Record operations](https://pocketbase.io/docs/js-records/), [PocketBase documentation, API rules and filters](https://pocketbase.io/docs/api-rules-and-filters/), [PocketBase documentation, Going to production](https://pocketbase.io/docs/going-to-production/), [PocketBase, FAQ](https://pocketbase.io/faq/).

Copy-paste prompt

## What prompt adds Esign Comply clickwrap to a PocketBase 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 PocketBase, 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 PocketBase

```
Add Esign Comply clickwrap to my PocketBase 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/pocketbase.md (the steps and the tested code for PocketBase)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

PocketBase facts
- There is no Esign Comply package for PocketBase. The hooks in pb_hooks run in PocketBase's embedded JavaScript engine, not in Node.js: no fetch, no setTimeout, no npm package that needs Node.js. Call the REST API with $http.send. In the browser, load the SDK from https://esigncomply.com/sdk/v1/esigncomply.js.
- The secret key is the environment variable ESIGNCOMPLY_API_KEY of the PocketBase process, read with $os.getenv. PocketBase loads no .env file. Never put the key in pb_public, in a collection or in a migration. Never print it.
- Every handler runs in a scope of its own and cannot see variables of its file. Put shared code in pb_hooks/esc.js and load it with require(`${__hooks}/esc.js`) inside each handler.
- Routes with routerAdd: GET /signup, GET /legal/{slug}, POST /api/ceremony, POST /api/signup/confirm. Never register a path PocketBase already serves under /api/: the server stops when it loads the hook.
- Keep the pinned version IDs and the receipt in a collection created by a migration in pb_migrations, with all five API rules null. Read its json field with getString() and JSON.parse, never with get().
- One PocketBase instance, one pb_data folder. A second instance with its own data cannot confirm a session of the first.
- Expect live records only where ESIGNCOMPLY_LIVE is "true": production.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony sends POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the collection, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html of GET /v1/documents/{id}/versions/{version}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm reads GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the row in the collection. Only then create the account, and store the record ID and the receipt in the same row.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:8090/signup --callback http://localhost:8090/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

3 things to watch

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

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

- **get() on a json field returns bytes, not your array**

  PocketBase's documentation says json field values are exported as a raw bytes array. In the test with version 0.42.3, `get()` on the field that held two IDs returned an array of 15 numbers. Compared with the versions of a record, that never matches. The quickstart reads the field with `getString()` and `JSON.parse`, and the confirm route then found the pinned versions.

  Source: [PocketBase documentation, Record operations](https://pocketbase.io/docs/js-records/), read on November 26, 2026.

- **A handler cannot see the variables of its own file**

  PocketBase's documentation says each handler is serialized and executed in an isolated context. In the test, a constant declared at the top of a hooks file was `undefined` inside a route, and the route that used it answered `400`. The quickstart keeps the signer, the IDs and the API call in `pb_hooks/esc.js` and loads it with `require()` inside every handler.

  Source: [PocketBase documentation, Extend with JavaScript](https://pocketbase.io/docs/js-overview/), read on November 26, 2026.

- **A hook route on a system path stops the server**

  PocketBase's documentation suggests a prefix such as `/api/myapp/` to avoid collisions with system routes. In the test, a hook that registered `GET /api/health`, a path PocketBase has, stopped the server when the hooks were reloaded, with a message that the two patterns conflict. `/api/ceremony` and `/api/signup/confirm` collided with nothing in version 0.42.3.

  Source: [PocketBase documentation, Routing](https://pocketbase.io/docs/js-routing/), read on November 26, 2026.

## Where are the PocketBase quickstart and the API reference?

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

- Quickstart

  **[PocketBase quickstart](https://esigncomply.com/docs/quickstart/pocketbase)**

  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 PocketBase?

The same record on every stack and platform. Your PocketBase 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 PocketBase

### How does test mode work on preview URLs with PocketBase?

A preview is another PocketBase process with the test key and a `pb_data` folder of its own, on a host that a test key refuses until you list that exact host under Domains as a test origin. PocketBase has no preview deployments of its own: its FAQ says it is self-hosted only. On `localhost` a test key works with no setup.

### Where should the receipt be stored with PocketBase?

In a collection whose five API rules are `null`, beside the signer ID and the record ID. In the test a guest and a signed-in user got `403` from the Web API, and the hooks read and wrote the row. The data is the `pb_data` folder of one server: back it up, and run one instance.

### Is there an Esign Comply package for PocketBase hooks?

No. The hooks run in PocketBase's embedded JavaScript engine, which its documentation says is not a Node.js environment. In the test with version 0.42.3, `fetch` and `setTimeout` were undefined and `require("esigncomply")` failed. The routes call the REST API with `$http.send`, and the browser loads the SDK from a script tag.

### Who can read the receipts in the PocketBase dashboard?

Every superuser. PocketBase's documentation says API rules are ignored for superusers, and in the test a superuser read the row, receipt included, while everyone else got `403`. The production guide recommends restricting superusers to specific IP addresses and lists MFA for them as an option.

### Was this code run on a production PocketBase server?

Not yet. It ran with the prebuilt PocketBase 0.42.3 executable on one machine, over plain HTTP on `localhost`, until the conformance check passed. The certificate that `serve` issues for a domain, the systemd service, backups and updates are from PocketBase's documentation and are proven only on a real server.

### Other platforms

- [Supabase](https://esigncomply.com/supabase)
- [Turso](https://esigncomply.com/turso)
- [Railway](https://esigncomply.com/railway)

### Stacks used with PocketBase

- [React](https://esigncomply.com/react)
- [Next.js](https://esigncomply.com/nextjs)
- [Go](https://esigncomply.com/go)

[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)

## Keep the key in your PocketBase hooks and the receipt in a locked collection. Leave the record to us.

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

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

PocketBase is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about PocketBase is from PocketBase's documentation or from a test run, as marked, on November 26, 2026. `/pocketbase.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.
