# Add e-signatures and clickwrap with Astro

> Build a signup clickwrap in Astro with esigncomply in on-demand endpoints, the key in astro:env/server and the browser SDK in a client script. Tested code.

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

Last updated November 26, 2026

To add e-signatures and clickwrap with Astro, install `esigncomply`, `@esigncomply/browser` and the Node adapter. An endpoint rendered on demand creates the session with the secret key from `astro:env/server`. The signup page stays static and attaches the browser SDK in a client script, and a second endpoint confirms the record. 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 Astro 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/astro.md (the steps and the tested code for Astro)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Astro facts
- Packages (the only ones that exist): esigncomply (server code, Node.js 20.19 or later) and @esigncomply/browser (the page). There is no Astro integration for Esign Comply.
- Astro prerenders every route unless the route says otherwise. Each endpoint and page that calls the API needs export const prerender = false, and the project needs an adapter: npx astro add node.
- Declare ESIGNCOMPLY_API_KEY in env.schema with envField.string({ context: "server", access: "secret" }) and import it from astro:env/server, in server code only. Pass it to new EsignComply(key): under astro dev the values of .env are not in process.env. Never give it a PUBLIC_ name.
- Server SDK calls return { data, error } and do not throw. Check error every time.
- Put the browser code in a plain <script> tag of the page. Astro bundles it and resolves the @esigncomply/browser import. Never import astro:env/server or the server module there.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.
- Print the document HTML with set:html. An expression in braces is escaped.
- Keep the pinned version IDs in the Astro session (context.session in an endpoint). It is stored on the server.

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. src/pages/api/ceremony.ts (POST, prerender = false): create the session with esc.sessions.create and an Idempotency-Key, save the pinned version IDs in the Astro session, and return only clientToken, apiUrl and documents.
4. src/pages/legal/[slug].astro (prerender = false): load the registered version from esc.documents.versions.getContent and render it inside <article data-esc-document> with set:html, unmodified.
5. src/pages/signup.astro: in the page's <script>, EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then ceremony.complete() in the submit handler. The checkbox has no checked attribute.
6. src/pages/api/signup/confirm.ts (POST, prerender = false): read the record with esc.records.get and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the server-owned state. Only then create the account.

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:4321/signup --callback http://localhost:4321/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.

## 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.
- An Astro project. To start one: `npm create astro@latest`. This page was run on Astro 7.4.13, in a project made from the minimal template.
- Node.js 22.23.4 or later, which Astro's documentation asks for. The `esigncomply` package needs 20.19 or later. This page was run on Node.js 24.22.1.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Add the Node adapter, then the server package for the endpoints and the browser SDK for the page:

```bash
npx astro add node
npm install esigncomply @esigncomply/browser
```

Astro builds static pages unless a route asks to be rendered on demand, and a route can only ask when the project has an adapter. `astro add node` installs `@astrojs/node` and writes it into `astro.config.mjs`. There is no Astro integration for Esign Comply to add: the browser SDK is headless, so you write the markup and it observes it.

## Step 2. Set the key

Put the key in `.env` in the project folder. Astro reads this file under `astro dev`.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Then declare each variable in `astro.config.mjs`. A variable with `context: "server"` and `access: "secret"` can be imported from `astro:env/server` only:

```js file="astro.config.mjs"
// astro.config.mjs
// @ts-check
import { defineConfig, envField } from "astro/config";
import node from "@astrojs/node";

const secret = /** @type {const} */ ({ context: "server", access: "secret" });

// https://astro.build/config
export default defineConfig({
  // Routes rendered on demand need an adapter. This one builds a Node.js server.
  adapter: node({ mode: "standalone" }),
  env: {
    schema: {
      // Server and secret: importable from astro:env/server only, read when the server runs, in no bundle.
      ESIGNCOMPLY_API_KEY: envField.string(secret),
      ESIGNCOMPLY_PROFILE_ID: envField.string(secret),
      ESIGNCOMPLY_TERMS_ID: envField.string(secret),
      ESIGNCOMPLY_PRIVACY_ID: envField.string(secret),
      // Optional: the SDK picks the API host from the key when this is not set.
      ESIGNCOMPLY_API_URL: envField.string({ ...secret, optional: true }),
      // "true" in production only.
      ESIGNCOMPLY_LIVE: envField.boolean({ ...secret, default: false }),
    },
  },
});
```

Astro's documentation says secret server variables are not part of the final bundle. After `astro build`, no file under `dist` held the key or the three IDs when this was checked. The three IDs come from step 3.

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

One module holds the client, the test signer and the constants the two endpoints share:

```ts file="src/lib/esigncomply.ts"
// src/lib/esigncomply.ts
import { EsignComply } from "esigncomply";
import {
  ESIGNCOMPLY_API_KEY,
  ESIGNCOMPLY_API_URL,
  ESIGNCOMPLY_LIVE,
  ESIGNCOMPLY_PRIVACY_ID,
  ESIGNCOMPLY_TERMS_ID,
} from "astro:env/server";

// Server code only. The key comes from astro:env/server: under astro dev it is not in process.env.
export const esc = new EsignComply(ESIGNCOMPLY_API_KEY, { baseUrl: ESIGNCOMPLY_API_URL });

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

export const DOCUMENTS: Record<string, string | undefined> = {
  terms: ESIGNCOMPLY_TERMS_ID,
  privacy: ESIGNCOMPLY_PRIVACY_ID,
};
export const SEALED = ["recorded", "timestamped", "anchored"];
// Test records in development, live records where ESIGNCOMPLY_LIVE is "true": production only.
export const LIVE = ESIGNCOMPLY_LIVE;
```

The client gets the key as an argument for a reason that is specific to Astro. Under `astro dev` the values of `.env` are in `astro:env/server` and not in `process.env`, which is where the SDK looks by default: a client created with no argument answered `missing_api_key` when this was tried.

A file under `src/pages/api` is an endpoint. This one creates the session and returns three values to the browser: the client token, the API URL and the pinned documents.

```ts file="src/pages/api/ceremony.ts"
// src/pages/api/ceremony.ts
import type { APIRoute } from "astro";
import { ESIGNCOMPLY_PROFILE_ID } from "astro:env/server";
import { DOCUMENTS, esc, signer } from "../../lib/esigncomply";

// Rendered on demand. Without this line Astro prerenders the route when it builds the site.
export const prerender = false;

// Step 4: create the session with the secret key. The browser gets the client token only.
export const POST: APIRoute = async ({ request, url, session }) => {
  // The page that runs the ceremony: the origin the browser reports, plus its path.
  const origin = request.headers.get("origin") ?? url.origin;

  const { data: created, error } = await esc.sessions.create(
    {
      profile: ESIGNCOMPLY_PROFILE_ID,
      signer,
      documents: [
        { document: DOCUMENTS.terms!, version: "current" },
        { document: DOCUMENTS.privacy!, version: "current" },
      ],
      context: { url: `${origin}/signup`, locale: "en-US", purpose: "account_signup" },
    },
    { idempotencyKey: `signup-${signer.external_id}-${crypto.randomUUID()}` },
  );
  if (error) return Response.json({ error: error.code }, { status: 502 });

  // The Astro session lives on the server. The browser holds only its ID, in a cookie.
  session?.set("pinnedVersions", created.documents.map((d) => d.version_id));
  return Response.json({ clientToken: created.client_token, apiUrl: created.api_url, documents: created.documents });
};
```

Two lines carry the Astro part. `export const prerender = false` makes Astro run the endpoint for each request. Without it the endpoint still answered under `astro dev`, with a warning in the log, and `astro build` turned it into a static file. And `session` is the Astro session: the pinned version IDs are stored on the server, and the browser gets a cookie that holds the session ID only.

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.

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button of your own markup, and reports each step from the signer's browser straight to Esign Comply. The page is `src/pages/signup.astro`:

```astro file="src/pages/signup.astro"
---
// src/pages/signup.astro
// No prerender export: Astro builds this page once, as static HTML.
// The script below asks the server for a session each time the page loads.
---

<!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>
      // Astro bundles this script for the browser: the import is resolved from node_modules.
      import { EsignComply, type Ceremony } from "@esigncomply/browser";

      const form = document.querySelector<HTMLFormElement>("#signup")!;
      const agree = document.querySelector<HTMLInputElement>("#agree")!;
      const submit = document.querySelector<HTMLButtonElement>("#create-account")!;
      const message = document.querySelector<HTMLElement>("#message")!;
      let ceremony: Ceremony | undefined;

      // One session per page load.
      async function start() {
        // Your endpoint creates the session and returns { clientToken, apiUrl, documents }. Never the secret key.
        const response = await fetch("/api/ceremony", { method: "POST" });
        if (!response.ok) throw new Error("We could not start the signup. Reload the page to try again.");
        const { clientToken, apiUrl, documents } = await response.json();

        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<HTMLAnchorElement>("#tos-link")!, document.querySelector<HTMLAnchorElement>("#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.
      }
      start().catch((error) => (message.textContent = error.message));

      form.addEventListener("submit", async (event) => {
        event.preventDefault();
        if (!ceremony) return;
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your endpoint 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 instanceof Error ? error.message : "Something went wrong.";
        }
      });
    </script>
  </body>
</html>
```

Each link opens a document page on your own origin, rendered on demand so it can read the version from the query string:

```astro file="src/pages/legal/[slug].astro"
---
// src/pages/legal/[slug].astro
import { DOCUMENTS, esc } from "../../lib/esigncomply";

// Rendered on demand: the page reads the version from the query string of each request.
export const prerender = false;

const documentId = DOCUMENTS[Astro.params.slug ?? ""];
if (!documentId) return new Response(null, { status: 404 });
const { data, error } = await esc.documents.versions.getContent(documentId, Astro.url.searchParams.get("v") ?? "current");
if (error) return new Response(null, { status: 404 });
---

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Document</title>
  </head>
  <body>
    <!-- set:html prints the registered version as it is. {data.html} would escape it. -->
    <article data-esc-document={data.version_id} set:html={data.html} />
  </body>
</html>
```

Start the app and open [http://localhost:4321/signup](http://localhost:4321/signup):

```bash
npm run dev
```

The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows a line such as:

```text
Account created. Record rec_quJxtM8NVmg8yEdC9GZy
```

Three details matter. The signup page has no `prerender` export, so Astro builds it once as static HTML, and the script asks for a session each time the page loads. The `<script>` tag has no attributes, so Astro bundles it: the build wrote it, with the browser SDK inside, to a file under `dist/client/_astro`. And the document page prints the HTML with `set:html`. Written as `{data.html}`, the same page arrived as `&lt;h1&gt;Terms of Service&lt;/h1&gt;` when this was tried, which is not the text that was registered.

The checkbox starts unchecked and disabled. The static 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 page's scripts held back, under `astro dev` and on the built server, a click on the box did nothing.

## Step 6. Confirm the record on the server

The result of `ceremony.complete()` was delivered to the browser, so your server does not trust it. A second endpoint reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one this server created the session for; and the document versions are exactly the ones in the Astro session. This step is never optional.

```ts file="src/pages/api/signup/confirm.ts"
// src/pages/api/signup/confirm.ts
import type { APIRoute } from "astro";
import { LIVE, SEALED, esc, signer } from "../../../lib/esigncomply";

export const prerender = false;

// Step 6: confirm the record with the secret key before the account exists.
export const POST: APIRoute = async ({ request, session }) => {
  const body = await request.json().catch(() => ({})); // an empty or malformed body is refused below
  const { data: record, error } = await esc.records.get(String(body.recordId));

  const pinned: string[] = (await session?.get("pinnedVersions")) ?? [];
  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([...pinned].sort());

  console.log(confirmed ? `confirmed ${record.id} (${record.status})` : "refused");
  if (!confirmed) return Response.json({ confirmed: false }, { status: 409 });
  // Only now create the account, and store record.id and record.receipt with it.
  return Response.json({ confirmed: true, recordId: record.id });
};
```

The server prints one line for each confirmation:

```text
confirmed rec_quJxtM8NVmg8yEdC9GZy (recorded)
```

In the test run the dev server ran in the background, and these lines were in `.astro/dev.log`.

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

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

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

A real record ID sent without the session cookie was answered `409` too: with no Astro session there are no pinned versions to compare it with.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this endpoint 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:4321/signup --callback http://localhost:4321/api/signup/confirm
```

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:4321/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_quJxtM8NVmg8yEdC9GZy  session ses_VxTYDNoNSqUxUxZm5fkc, 5 events
  768x1024   record rec_2j1Ygcf1EYCKA9AWBh22  session ses_qdPpRShhM5ZHrt4HVVLk, 5 events
  1440x900   record rec_XNAt3AC8X7KkBcQepf7e  session ses_U5GGiPnavrMd7LDei1cK, 5 events

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

This run was made under `astro dev`, with the dev toolbar on the page.

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 switch the app over:

- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. From then on the confirm endpoint refuses every test record there.
- Build the app and give the server its variables. The built server does not read `.env`: started with `node ./dist/server/entry.mjs` and no variables, it served the static signup page and answered the session request with `500` and `EnvInvalidVariables`. Started with `node --env-file=.env ./dist/server/entry.mjs`, the same build sealed a record and the page showed `Account created. Record rec_fnNdJaYxkWm68MTwp2Fh`.
- Decide where sessions live. The Node adapter keeps Astro sessions in files on the server's disk: in the test run they were under `node_modules/.astro/sessions`. With more than one server, set a shared session driver in `astro.config.mjs`.
- Store `record.id` and `record.receipt` beside the user.

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

- **The session endpoint works under `astro dev` and answers with a page after the build.** The endpoint has no `export const prerender = false`. Under `astro dev` the log says `POST requests are not available in static endpoints`. After `astro build` an endpoint like that was a static file when this was tried, and the built server answered a `POST` to it with status `200` and the HTML of Astro's 404 page: the handler never ran.
- **`EnvInvalidVariables` or `missing_api_key` from the session endpoint.** The key did not reach the server. On the built server, set the variables in its environment: Astro names each missing one. Under `astro dev`, pass the key from `astro:env/server` to the client: with no argument the SDK answers [`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 from `astro dev --host`. 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).
- **`429` when the confirm endpoint reads the record.** The endpoint 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, with the session cookie, all answered `200`, two of them a second later than the others: the API had answered those two reads with `429`. 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 Astro quickstart

### Why does the signup page stay static?

Because nothing on it depends on the request. The session is created by the endpoint when the page's script asks for it, so the HTML is the same for every visitor and Astro can build it once. Only the two endpoints and the document pages are rendered on demand.

### What happens when the client script imports astro:env/server?

The build stops. `astro build` ended with `ServerOnlyModule` and the message that the module is only available server-side. Under `astro dev` the page loaded, and the browser's request for the module was answered `500` with the same message, so the script never ran.

### Where does Astro keep the pinned versions?

In the Astro session, which the Node adapter stores in files on the server. In the test run the browser got a cookie named `astro-session` with a 36-character ID, marked `HttpOnly` and `SameSite=Lax`, and the version IDs were in a file named after that ID. The built server added `Secure` to the cookie.

### Does Astro's origin check get in the way of the session request?

Not from your own page. When this was tested, a `POST` with no body and no `Origin` header was answered `200`, and the same request with the `Origin` of another site was answered `403` with `Cross-site POST form submissions are forbidden`. A JSON `POST` from another origin reached the confirm endpoint, which refused the made-up record with `409`.

### Does the Astro quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for Astro](https://esigncomply.com/astro): what the integration gives you on this stack, with the things to watch for.
- [Browser SDK](https://esigncomply.com/docs/sdk/browser.md): every method the page calls, and what each one records.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Node SDK](https://esigncomply.com/docs/sdk/node.md): every method the endpoints call, the endpoint behind it, and the errors.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
