# Add e-signatures and clickwrap on Fly.io

> Run a signup clickwrap on Fly.io with the esigncomply package in a Node.js app, the key as an app secret, and Managed Postgres for the receipt.

Source: https://esigncomply.com/docs/quickstart/fly-io

Last updated November 26, 2026

To add e-signatures and clickwrap on Fly.io, run the `esigncomply` package in a Node.js app and store the secret key with `fly secrets set`. The app creates the session and confirms the record, and a Managed Postgres database keeps the pinned versions and the receipt for every Machine. 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 app on Fly.io: 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/fly-io.md (the steps and the tested code for Fly.io)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Fly.io 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.
- The secret key is the app secret ESIGNCOMPLY_API_KEY, set with "fly secrets set". Never put it in fly.toml, in the Dockerfile or in the image. Never print it.
- Listen on 0.0.0.0 on the internal_port of fly.toml. PORT is not among the variables Fly.io sets in a Machine.
- The image's command is ["node", "server.js"], not npm, so the process receives the stop signal itself. That signal is SIGINT unless fly.toml sets kill_signal: handle SIGINT and SIGTERM.
- An app with a service runs on two Machines, and Fly Proxy stops idle ones. Keep the pinned version IDs in Postgres (DATABASE_URL, set by "fly mpg attach"), never in a variable of the process. Create the table in the release_command of fly.toml.
- Expect live records only where the app secret ESIGNCOMPLY_LIVE is "true". A review app is another app with secrets of its own: give it the test key.
- 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 creates the session with esc.sessions.create and an Idempotency-Key, saves the signer ID and the pinned version IDs in Postgres, 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.
6. Server: POST /api/signup/confirm 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 row in Postgres. 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:3000/signup --callback http://localhost:3000/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

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

The rest of this page is the same integration by hand, in eight steps. Steps 1 to 7 run on your machine with Node.js and a Postgres database in Docker. Step 8 is the part that happens on Fly.io.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- Node.js 20.19 or later, which the `esigncomply` package requires. This page was run on Node.js 24.22.1, on the machine and in the image.
- Docker, for a Postgres database on your machine and to build the image.
- A Fly.io account and `flyctl`, when you reach step 8. Steps 1 to 7 need neither.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Install the server package and the Postgres driver 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 scripts.start="node server.js"
npm install esigncomply pg
mkdir public
```

`npm pkg set type=module` matters: `esigncomply` is an ES module and `server.js` uses `import`.

## Step 2. Set the key

On your machine the key goes in `.env`, with the address of the local database. On Fly.io both are app secrets: you set the key with `fly secrets set`, and `fly mpg attach` sets `DATABASE_URL`. Neither is ever committed.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
DATABASE_URL=postgresql://postgres:local@127.0.0.1:5432/esigncomply
```

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

Start a Postgres database on your machine. It stands in for the Managed Postgres cluster of step 8:

```bash
docker run -d --name esc-postgres -p 127.0.0.1:5432:5432 \
  -e POSTGRES_PASSWORD=local -e POSTGRES_DB=esigncomply \
  public.ecr.aws/docker/library/postgres:17-alpine
```

One module holds everything that touches the database: the versions a session pinned, and later the record and its receipt.

```js file="store.js"
// store.js
import pg from "pg";

// fly mpg attach sets DATABASE_URL as a secret of the app: the connection string of the Managed Postgres cluster.
// Every Machine opens its own pool on the same database, so they all see the same rows.
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
// When the database closes an idle connection, the pool emits an error. With no listener, Node.js exits.
pool.on("error", (error) => console.error(`postgres: ${error.message}`));

// One row per signer: the versions the session pinned, then the record and its receipt.
export async function migrate() {
  await pool.query(`
    CREATE TABLE IF NOT EXISTS esc_acceptances (
      signer_id    text PRIMARY KEY,
      version_ids  jsonb NOT NULL,
      record_id    text,
      receipt      text,
      confirmed_at timestamptz
    )`);
}

export async function savePinned(signerId, versionIds) {
  await pool.query(
    `INSERT INTO esc_acceptances (signer_id, version_ids) VALUES ($1, $2)
     ON CONFLICT (signer_id) DO UPDATE SET version_ids = EXCLUDED.version_ids`,
    [signerId, JSON.stringify(versionIds)],
  );
}

export async function getPinned(signerId) {
  const { rows } = await pool.query("SELECT version_ids FROM esc_acceptances WHERE signer_id = $1", [signerId]);
  return rows[0]?.version_ids ?? [];
}

export async function saveReceipt(signerId, recordId, receipt) {
  await pool.query("UPDATE esc_acceptances SET record_id = $2, receipt = $3, confirmed_at = now() WHERE signer_id = $1", [signerId, recordId, receipt]);
}

export async function ready() {
  await pool.query("SELECT 1");
}

export async function close() {
  await pool.end();
}
```

The state is in Postgres and not in a variable of the process for two reasons. Fly.io creates two Machines for an app that has a service, and either one can answer a request. And with `auto_stop_machines`, Fly Proxy stops a Machine when the app is idle, and a stopped Machine starts again as a new process.

A second file creates the table. On Fly.io it is the release command, which runs in a temporary Machine before the others are updated:

```js file="migrate.js"
// migrate.js: the release command. Fly.io runs it in a temporary Machine before it updates the others.
import { close, migrate } from "./store.js";

await migrate();
console.log("table esc_acceptances ready");
await close();
```

The server creates the session in `POST /api/ceremony` and 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 { randomUUID } from "node:crypto";
import { EsignComply } from "esigncomply";
import { close, getPinned, ready, savePinned, saveReceipt } from "./store.js";

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

// The signer. In your app this is the signed-in user, or the account you are about to create.
const signer = {
  external_id: "user_7c1d",
  email: "dana@example.org",
  name: "Dana Whitfield",
  class: "consumer",
  country: "US",
  region: "US-CA",
};

const DOCUMENTS = {
  terms: process.env.ESIGNCOMPLY_TERMS_ID,
  privacy: process.env.ESIGNCOMPLY_PRIVACY_ID,
};
const SEALED = ["recorded", "timestamped", "anchored"];
// ESIGNCOMPLY_LIVE is a secret of the production app, set beside the live key. A review app is
// another Fly App with secrets of its own, so it never inherits the value.
const LIVE = process.env.ESIGNCOMPLY_LIVE === "true";

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

async function body(req) {
  let text = "";
  for await (const chunk of req) text += chunk;
  return text ? JSON.parse(text) : {};
}

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

  // The path of the check in fly.toml: Fly Proxy sends requests only to Machines that pass it.
  if (req.method === "GET" && url.pathname === "/health") {
    try {
      await ready();
      return json(res, 200, { ok: true });
    } catch {
      return json(res, 503, { ok: false });
    }
  }

  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") {
    const { data: session, error } = await esc.sessions.create(
      {
        profile: process.env.ESIGNCOMPLY_PROFILE_ID,
        signer,
        documents: [
          { document: DOCUMENTS.terms, version: "current" },
          { document: DOCUMENTS.privacy, version: "current" },
        ],
        // The page that runs the ceremony: the origin the browser reports, plus its path.
        context: { url: `${req.headers.origin ?? url.origin}/signup`, locale: "en-US", purpose: "account_signup" },
      },
      { idempotencyKey: `signup-${signer.external_id}-${randomUUID()}` },
    );
    if (error) return json(res, 502, { error: error.code });
    // In Postgres, not in memory: the confirmation can reach the other Machine.
    await savePinned(signer.external_id, session.documents.map((d) => d.version_id).sort());
    return json(res, 200, { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });
  }

  // Step 6: confirm the record with the secret key before the account exists.
  if (req.method === "POST" && url.pathname === "/api/signup/confirm") {
    const { recordId } = await body(req);
    const { data: record, error } = await esc.records.get(String(recordId));
    const expected = await getPinned(signer.external_id);
    const confirmed =
      !error &&
      SEALED.includes(record.status) &&
      record.livemode === LIVE &&
      record.signer.external_id === signer.external_id &&
      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 json(res, 409, { confirmed: false });
    // Only now create the account. The record ID and the receipt go in the same row.
    await saveReceipt(signer.external_id, record.id, record.receipt);
    return json(res, 200, { confirmed: true, recordId: record.id });
  }

  json(res, 404, { error: "not_found" });
}

// A route that throws must not take the Machine down with it: answer 500 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" });
  });
});

// PORT is not among the variables Fly.io sets in a Machine. Listen on 0.0.0.0, on the internal_port of fly.toml.
const port = Number(process.env.PORT ?? 3000);
server.listen(port, "0.0.0.0", () => console.log(`http://localhost:${port}/signup`));

// Fly.io stops a Machine with SIGINT unless fly.toml names another signal. Finish the open
// requests, close the pool, exit.
for (const signal of ["SIGINT", "SIGTERM"]) {
  process.on(signal, () => {
    server.close(() => close().finally(() => process.exit(0)));
    server.closeIdleConnections();
  });
}
```

The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

Every route runs inside `handle`, so a route that throws (the database gone for one request, a body that is not JSON) answers `500` and is logged instead of ending the process. In the test, with the Postgres container stopped, the session route answered `500` and the same container served the next request, where the `async` function passed to `createServer` itself ended the process with exit code 1.

Create the table, then start the server:

```bash
node --env-file=.env migrate.js
node --env-file=.env server.js
```

```text
table esc_acceptances ready
http://localhost:3000/signup
```

## 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 and the two 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; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="assent">
        <!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
        <label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
        <p>
          By checking the box and clicking Create account, you agree to the
          <a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
          <a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
        </p>
        <button id="create-account" type="submit" disabled>Create account</button>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      const { clientToken, apiUrl, documents } = await response.json();

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

      // Point each link at the exact version this session pinned, then report it.
      const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
      for (const [i, link] of links.entries()) {
        link.search = "?v=" + documents[i].version_id;
        await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, links, checkbox, button
        checkbox: agree,
        submit,
      });
      agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.

      document.querySelector("#signup").addEventListener("submit", async (event) => {
        event.preventDefault();
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your server confirms the record before anything is granted.
          const confirmed = await fetch("/api/signup/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ recordId: result.recordId }),
          });
          message.textContent = confirmed.ok
            ? `Account created. Record ${result.recordId}`
            : "We could not confirm whether your acceptance was recorded. Please wait while we check.";
        } catch (error) {
          message.textContent = error.message;
        }
      });
    </script>
  </body>
</html>
```

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

```text
Account created. Record rec_CC1yr4Ad7KhmejbX28ub
```

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. `POST /api/signup/confirm` in `server.js` reads the record with the secret key and the pinned versions from Postgres, and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this app expects; the signer is the one the session was created for; and the document versions are exactly the ones it pinned. This step is never optional.

`ESIGNCOMPLY_LIVE` is an app secret you set on the production app only, beside the live key. The server expects live records only there. On your machine the variable is not set, so test records are accepted.

The server logs one line for each confirmation, and the row then holds the record ID and the receipt:

```text
confirmed rec_CC1yr4Ad7KhmejbX28ub (recorded)
```

A record ID that was made up is refused with status `409`:

```bash
curl -s -X POST http://localhost:3000/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

In the test, a second container that was started after the session existed confirmed the record: the pinned versions came from Postgres. A container started with `ESIGNCOMPLY_LIVE=true` refused a test record with `409`.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route.

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

The report for this page's code, run in the image built from the Dockerfile of step 8, 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/signup/confirm answered 409.

Ceremonies
  390x844    record rec_NdRPGiFNGNvxFwMk0qws  session ses_E16dPJZu6DnPusFebcXG, 5 events
  768x1024   record rec_5uHu3dRMGd6YqT2oWT56  session ses_bACQh9en8HJaxWrG3Ww8, 5 events
  1440x900   record rec_bsY90KMCMPUMaG6HxiUQ  session ses_kDHtnnL2k6oqTvRcScyZ, 5 events

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

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then set up the Fly.io app. The settings below are from Fly.io's own documentation, checked on November 25, 2026: [Create an app with Fly Launch](https://docs.fly.io/launch/create), [App configuration (fly.toml)](https://docs.fly.io/reference/configuration), [Secrets and Fly Apps](https://docs.fly.io/apps/secrets), [App Availability and Resiliency](https://docs.fly.io/apps/app-availability), [Autostop/autostart Machines](https://docs.fly.io/launch/autostop-autostart), [Health Checks](https://docs.fly.io/reference/health-checks), [The Machine Runtime Environment](https://docs.fly.io/machines/runtime-environment), [fly mpg attach](https://docs.fly.io/flyctl/cmd/fly_mpg_attach), [Git Branch Preview Environments on Github](https://docs.fly.io/blueprints/review-apps-guide) and [Custom domains](https://docs.fly.io/networking/custom-domain).

**The Dockerfile.** `fly launch` writes a Dockerfile for a JavaScript app with Fly.io's generator, `@flydotio/dockerfile`. As generated for this project, its last line was `CMD [ "npm", "run", "start" ]`. Run the generator yourself with its `--cmd` option, so that Node.js is the main process of the image:

```bash
npx @flydotio/dockerfile --cmd '["node", "server.js"]'
```

This is the file version 0.7.15 of the generator wrote. `fly launch` keeps a Dockerfile that is already there:

```dockerfile file="Dockerfile"
# syntax = docker/dockerfile:1

# Adjust NODE_VERSION as desired
ARG NODE_VERSION=24.22.1
FROM node:${NODE_VERSION}-slim AS base

LABEL fly_launch_runtime="Node.js"

# Node.js app lives here
WORKDIR /app

# Set production environment
ENV NODE_ENV="production"


# Throw-away build stage to reduce size of final image
FROM base AS build

# Install packages needed to build node modules
RUN apt-get update -qq && \
    apt-get install --no-install-recommends -y build-essential node-gyp pkg-config python-is-python3

# Install node modules
COPY package-lock.json package.json ./
RUN npm ci

# Copy application code
COPY . .


# Final stage for app image
FROM base

# Copy built application
COPY --from=build /app /app

# Start the server by default, this can be overwritten at runtime
EXPOSE 3000
CMD ["node", "server.js"]
```

The generator also writes `.dockerignore`, which keeps `.env` out of the image, and records the option under `dockerfile` in `package.json`:

```text file=".dockerignore"
/.git
/node_modules
.dockerignore
.env
Dockerfile
fly.toml
```

The command matters because Fly.io sends the stop signal to the main process of the image. In the test, the image as first generated was still running 15 seconds after `SIGINT`, because npm was the main process. With `node server.js` it closed the database pool and exited with code 0 in under a second.

**The app file.** `fly.toml` names the port, the health check and the release command. Change `app` to the name of your app:

```toml file="fly.toml"
# fly.toml
app = "esigncomply-quickstart"
primary_region = "iad"

[deploy]
  release_command = "node migrate.js"

[http_service]
  internal_port = 3000
  force_https = true
  auto_stop_machines = "stop"
  auto_start_machines = true
  min_machines_running = 0

  [[http_service.checks]]
    grace_period = "10s"
    interval = "30s"
    method = "GET"
    timeout = "5s"
    path = "/health"
```

`internal_port` has to be the port the server listens on: `PORT` is not among the variables Fly.io sets in a Machine, so `server.js` falls back to `3000`. Fly Proxy sends requests only to Machines that pass the check on `/health`. Fly.io sends `SIGINT` to stop a Machine unless `kill_signal` names another signal, and `server.js` handles both `SIGINT` and `SIGTERM`.

**The app, the database and the key.** Create the app from this file without deploying it, create a Managed Postgres cluster and attach it, then set the secrets:

```bash
fly launch --no-deploy --copy-config
fly mpg create
fly mpg attach <CLUSTER_ID> -a <your-app>
fly secrets set ESIGNCOMPLY_API_KEY=esc_live_us_... ESIGNCOMPLY_LIVE=true \
  ESIGNCOMPLY_PROFILE_ID=prof_... ESIGNCOMPLY_TERMS_ID=doc_... ESIGNCOMPLY_PRIVACY_ID=doc_...
fly deploy
```

`fly mpg attach` sets `DATABASE_URL` as a secret of the app, with the connection string of the cluster. Secrets are stored in an encrypted vault and reach every Machine of the app as environment variables. `fly secrets set` restarts the Machines of a deployed app, and `fly deploy` runs the release command in a temporary Machine before it updates them.

**Review apps and test mode.** Fly.io's review apps are separate apps, one for each pull request, created by the `superfly/fly-pr-review-apps` GitHub Action. A new app has no secrets: the workflow passes them in from GitHub secrets. Give it the test key and the test IDs, and leave `ESIGNCOMPLY_LIVE` out. By default a review app answers on `pr-<PR number>-<repository owner>-<repository name>.fly.dev`, and 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": ["pr-12-acme-web.fly.dev"] }'
```

List exact hosts, up to 25. An entry also covers its subdomains, so never list the shared suffix `fly.dev`.

**The production domain.** Register your custom domain and verify it with one DNS record. `fly certs add` attaches the domain to the app. If production runs on its `fly.dev` host, you cannot add DNS records there, so the domain verifies with a file: serve the token as plain text at `/.well-known/esigncomply.txt`. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).

**The image on your machine.** To run the image before you deploy it, build it with Docker and start it against the database of step 4. The second command is the release command, run the way Fly.io runs it: in place of the image's command.

```bash
docker build -t esigncomply-quickstart .
docker run --rm --network host --env-file .env esigncomply-quickstart node migrate.js
docker run --rm --network host --env-file .env esigncomply-quickstart
```

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` in a review app.** A review app is a new app, with no secrets until the workflow passes them in. Add the test key to the secrets the workflow sets. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`domain_mismatch` on a `fly.dev` host.** The host is not a test origin of your domain. Add the exact host under Domains in the dashboard. Test keys work on `localhost` with no setup. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch) and [Test mode](https://esigncomply.com/docs/guides/test-mode.md).
- **A Machine takes seconds to stop, or logs `npm error signal SIGTERM`.** The image starts the app through npm, so the stop signal reaches npm and not your server. In a test, that image was still running 15 seconds after `SIGINT`, and after `SIGTERM` it exited with code 1. Make `node server.js` the command of the image.
- **`429` when the confirm route reads the record.** The route needs no retry loop: the `esigncomply` package waits for the time in `Retry-After` and tries again, up to twice. In the test, four confirmations sent at once for one record all answered `200`, two of them a second later than the others. Four reads sent at once through the package in the same image showed why: two got `429` with `Retry-After: 1` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded) and [Retries and timeouts](https://esigncomply.com/docs/sdk/node.md#retries-and-timeouts).

## Questions about the Fly.io quickstart

### Why Postgres and not a variable in the process?

Because Fly.io creates two Machines for an app with a service, and Fly Proxy stops idle Machines when `auto_stop_machines` is on. The confirmation can reach a Machine that never saw the session. In the test, two Node.js processes with a `Map` ended in `409`, and with Postgres a second container confirmed the record.

### Why is the image's command node server.js and not npm run start?

Because Fly.io sends the stop signal to the main process, and the signal is `SIGINT` unless `fly.toml` sets `kill_signal`. In the test, the image as generated, with `npm run start`, was still running 15 seconds after `SIGINT`. With `node server.js` it closed the pool and exited with code 0 in under a second.

### Where does the port come from on Fly.io?

From your own code and `fly.toml`. `PORT` is not among the variables Fly.io's documentation lists for a Machine, so the server falls back to 3000, and `internal_port` in `fly.toml` has to be the same number. The server listens on `0.0.0.0`, which is where Fly Proxy reaches it.

### Was fly.toml validated?

No. `fly config validate` checks the file against the Fly.io platform and needs a login, so it was not run. The file was written from Fly.io's configuration reference. The Dockerfile came from Fly.io's own generator, and the image built from it passed the conformance check.

### Was this quickstart deployed to Fly.io?

Not yet. The code ran in the image built from the generated Dockerfile, with the release command run in place of the image's command. `fly launch`, `fly deploy`, secrets, Managed Postgres, Machines, the health check and the `fly.dev` host are proven only by a deployment.

## Next steps

- [E-signatures and clickwrap on Fly.io](https://esigncomply.com/fly-io): how the pieces fit on this platform, with the things to watch for.
- [Register a domain](https://esigncomply.com/docs/guides/domains.md): DNS and file verification, statuses, and test origins.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Add e-signatures and clickwrap with Node.js](https://esigncomply.com/docs/quickstart/nodejs.md): the same server without a database.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
