# Add e-signatures and clickwrap on Vercel

> Run a signup clickwrap on Vercel with a Next.js Route Handler, keys scoped to Production and Preview, VERCEL_ENV and a signed cookie for state.

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

Last updated November 26, 2026

To add e-signatures and clickwrap on Vercel, keep the secret key in an Environment Variable, the test key for Preview and Development and the live key for Production. A Next.js Route Handler, which runs as a Vercel Function, creates the session and another confirms the record against `VERCEL_ENV`. 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, v0 or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Next.js app on Vercel: 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/vercel.md (the steps and the tested code for Vercel)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Vercel facts
- Packages (the only ones that exist): esigncomply (server), @esigncomply/react (hooks) and @esigncomply/browser.
- The secret key is the Environment Variable ESIGNCOMPLY_API_KEY: the test key for Preview and Development, the live key for Production only. Never give it a NEXT_PUBLIC_ name. Never print it.
- Expect live records only when process.env.VERCEL_ENV is "production". A preview deployment also has NODE_ENV "production", so NODE_ENV cannot tell them apart.
- Two requests can run in two function instances. Keep the pinned version IDs in the database, or in an httpOnly cookie signed with a secret. Never in memory.
- A preview deployment runs on its own vercel.app host. Test keys refuse that host until it is listed under Domains as a test origin. List the branch URL, never the shared suffix vercel.app.
- The form is in the server HTML before the page hydrates: 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. Route Handler app/api/ceremony/route.ts: create the session with esc.sessions.create and an Idempotency-Key, save the signer ID and the pinned version IDs in server-owned state, and return only clientToken, apiUrl and documents.
4. Server Component app/legal/[slug]/page.tsx: render the registered version from esc.documents.versions.getContent inside <article data-esc-document>, unmodified.
5. Client component: useCeremony({ clientToken, apiUrl }), useDocument for each link, ceremony.observeAssent({ region, checkbox, submit }) from an effect, then ceremony.complete() in the submit handler. Request the session once per page load, from a promise kept outside the component.
6. Route Handler app/api/signup/confirm/route.ts: read the record with esc.records.get and require: status is "recorded", "timestamped" or "anchored"; livemode equals (VERCEL_ENV === "production"); 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: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. Step 8 is the part that happens in the Vercel dashboard.

## 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.
- A Next.js app on the App Router. To start one: `npx create-next-app@latest`. This page was run on Next.js 16.4.6.
- A Vercel project for the app, when you reach step 8. Steps 1 to 7 need no Vercel account.
- `curl` and `jq` for steps 2 and 3.

## Step 1. Install

Install the server package, the hooks, the browser SDK, and `server-only`, which keeps the server modules out of client code:

```bash
npm install esigncomply @esigncomply/react @esigncomply/browser server-only
```

## Step 2. Set the key

On your machine the key goes in `.env.local`, beside a second secret that signs the state cookie of step 4. Generate that one with Node.js:

```bash
node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))"
```

```bash
# .env.local (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
CEREMONY_STATE_SECRET=the-value-the-command-printed
```

On Vercel the same names are Environment Variables of the project, and each one is applied to the environments you choose: Production, Preview, Development. That choice is the whole key policy: the test key for Preview and Development, the live key for Production. Step 8 has the commands.

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.local; 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.local`. 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 server-only module holds the client, the test signer, and the one line that is specific to Vercel: `LIVE`.

```ts file="lib/esigncomply.ts"
// lib/esigncomply.ts
import "server-only"; // the build fails if a client component imports this file
import { EsignComply } from "esigncomply";

export const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!);

// Vercel sets VERCEL_ENV on every deployment: "production", "preview" or "development".
// Production holds the live key and accepts live records only.
export const LIVE = process.env.VERCEL_ENV === "production";

// 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: process.env.ESIGNCOMPLY_TERMS_ID,
  privacy: process.env.ESIGNCOMPLY_PRIVACY_ID,
};
```

Vercel sets `VERCEL_ENV` to `production`, `preview` or `development` on every deployment. `NODE_ENV` cannot do this job: `next build` sets it to `production` for preview deployments too.

Two requests on Vercel can run in two function instances, so the state the confirmation compares against cannot sit in memory. This module puts it in an httpOnly cookie, signed so that the browser can carry it and cannot change it. A table in your database does the same job, and you need one anyway to keep the receipt.

```ts file="lib/ceremony-state.ts"
// lib/ceremony-state.ts
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";
import { cookies } from "next/headers";

// Two requests on Vercel can run in two function instances, so what this server pinned cannot
// live in memory. It travels in an httpOnly cookie signed with CEREMONY_STATE_SECRET: the browser
// carries it and cannot change it. A table in your database does the same job.
export interface Pinned {
  signerId: string;
  versionIds: string[];
}

const COOKIE = "esc_ceremony";
const MAX_AGE = 30 * 60; // seconds: the lifetime of a session

function sign(value: string): string {
  const secret = process.env.CEREMONY_STATE_SECRET;
  if (!secret) throw new Error("CEREMONY_STATE_SECRET is not set");
  return createHmac("sha256", secret).update(value).digest("base64url");
}

export async function savePinned(pinned: Pinned): Promise<void> {
  const value = Buffer.from(JSON.stringify({ ...pinned, exp: Date.now() + MAX_AGE * 1000 })).toString("base64url");
  (await cookies()).set(COOKIE, `${value}.${sign(value)}`, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    path: "/",
    maxAge: MAX_AGE,
  });
}

export async function loadPinned(): Promise<Pinned | null> {
  const [value, mac] = ((await cookies()).get(COOKIE)?.value ?? "").split(".");
  if (!value || !mac) return null;
  const expected = Buffer.from(sign(value));
  const given = Buffer.from(mac);
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
  const state = JSON.parse(Buffer.from(value, "base64url").toString()) as Pinned & { exp: number };
  return state.exp > Date.now() ? { signerId: state.signerId, versionIds: state.versionIds } : null;
}
```

A Route Handler creates the session. On Vercel it runs as a Vercel Function, and the secret key never leaves it.

```ts file="app/api/ceremony/route.ts"
// app/api/ceremony/route.ts
import { randomUUID } from "node:crypto";
import { savePinned } from "@/lib/ceremony-state";
import { DOCUMENTS, esc, signer } from "@/lib/esigncomply";

// A Route Handler runs as a Vercel Function. The secret key never leaves it.
export async function POST(request: Request) {
  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 origin the browser reports: localhost, a preview URL or your production domain.
      context: { url: `${request.headers.get("origin") ?? new URL(request.url).origin}/signup`, locale: "en-US", purpose: "account_signup" },
    },
    { idempotencyKey: `signup-${signer.external_id}-${randomUUID()}` },
  );
  if (error) return Response.json({ error: error.code, message: error.message }, { status: 502 });

  await savePinned({ signerId: signer.external_id, versionIds: session.documents.map((d) => d.version_id) });
  return Response.json({ clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });
}
```

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 signup page is a client component. The hooks render nothing: `useCeremony` attaches to the session, `useDocument` reports each document link, and `observeAssent` watches the checkbox, the notice and the button you built. Each step goes from the signer's browser straight to Esign Comply.

```tsx file="app/signup/page.tsx"
// app/signup/page.tsx
"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import { useCeremony, useDocument } from "@esigncomply/react";

interface Ceremony {
  clientToken: string;
  apiUrl: string;
  documents: Array<{ version_id: string }>;
}

// One session per page load. React runs effects twice in development,
// so the request is kept at module level and both runs share it.
let ceremonyRequest: Promise<Ceremony> | undefined;
function requestCeremony(): Promise<Ceremony> {
  ceremonyRequest ??= fetch("/api/ceremony", { method: "POST" }).then((response) => response.json());
  return ceremonyRequest;
}

// Document links are underlined and differ from the text around them by at least 3 to 1 (rule CR-05).
const LINK = { color: "#0b57d0", textDecoration: "underline" };

export default function SignupPage() {
  const [session, setSession] = useState<Ceremony | null>(null);
  useEffect(() => {
    let mounted = true;
    void requestCeremony().then((value) => mounted && setSession(value));
    return () => {
      mounted = false;
    };
  }, []);

  const { ceremony, canComplete, error } = useCeremony({ clientToken: session?.clientToken, apiUrl: session?.apiUrl });
  const [termsId, privacyId] = (session?.documents ?? []).map((d) => d.version_id);
  const terms = useDocument<HTMLAnchorElement>(ceremony, { versionId: termsId, mode: "hyperlink" });
  const privacy = useDocument<HTMLAnchorElement>(ceremony, { versionId: privacyId, mode: "hyperlink" });

  const assentRef = useRef<HTMLDivElement>(null);
  const checkboxRef = useRef<HTMLInputElement>(null);
  const submitRef = useRef<HTMLButtonElement>(null);
  const [ready, setReady] = useState(false); // true once the SDK observes the checkbox
  const [message, setMessage] = useState("");

  // Observe the assent controls once both documents are presented.
  useEffect(() => {
    if (!ceremony || !terms.presented || !privacy.presented) return;
    void ceremony
      .observeAssent({
        region: assentRef.current, // notice, links, checkbox, button
        checkbox: checkboxRef.current,
        submit: submitRef.current,
      })
      .then(() => setReady(true));
  }, [ceremony, terms.presented, privacy.presented]);

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    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. The Vercel Function 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 }),
      });
      setMessage(
        confirmed.ok
          ? `Account created. Record ${result.recordId}`
          : "We could not confirm whether your acceptance was recorded. Please wait while we check.",
      );
    } catch (err) {
      setMessage(err instanceof Error ? err.message : "Something went wrong.");
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <h1>Create account</h1>
      <div ref={assentRef}>
        {/* The form is in the server HTML, so the box stays disabled until the SDK watches it. Only the user changes it. */}
        <label>
          <input ref={checkboxRef} type="checkbox" disabled={!ready} /> 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 ref={terms.ref} href={`/legal/terms?v=${termsId ?? ""}`} style={LINK}>Terms of Service</a> and acknowledge the{" "}
          <a ref={privacy.ref} href={`/legal/privacy?v=${privacyId ?? ""}`} style={LINK}>Privacy Notice</a>.
        </p>
        <button ref={submitRef} type="submit" disabled={!canComplete}>
          Create account
        </button>
      </div>
      <p role="alert">{message || error?.message}</p>
    </form>
  );
}
```

Each link opens a document page on your own domain that renders the registered version, unmodified:

```tsx file="app/legal/[slug]/page.tsx"
// app/legal/[slug]/page.tsx
import { notFound } from "next/navigation";
import { DOCUMENTS, esc } from "@/lib/esigncomply";

// /legal/terms?v=dv_... renders one registered version, unmodified.
export default async function LegalPage({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ v?: string }>;
}) {
  const { slug } = await params;
  const { v } = await searchParams;
  const documentId = DOCUMENTS[slug];
  if (!documentId) notFound();

  const { data, error } = await esc.documents.versions.getContent(documentId, v ?? "current");
  if (error || !data.html) notFound();

  return <article data-esc-document={data.version_id} dangerouslySetInnerHTML={{ __html: data.html }} />;
}
```

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

```bash
npm run dev
```

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

```text
Account created. Record rec_BLxiMko5JhhErbxqtVmK
```

The checkbox is disabled until the SDK observes it. Next.js sends the form as HTML before the script loads, and the session arrives after the page hydrates: a box ticked that early stays ticked and fails [CR-01](https://esigncomply.com/docs/conformance.md#cr-01). In two tests, one with the page's scripts held back and one with the session request held back, the box was disabled and a click on it did nothing. The box is uncontrolled and has no `defaultChecked`: only the user changes it.

## 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 Route Handler reads the signed cookie and the record, and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` equals `LIVE`; the signer is the one this server created the session for; and the document versions are exactly the ones it pinned. This step is never optional.

```ts file="app/api/signup/confirm/route.ts"
// app/api/signup/confirm/route.ts
import { loadPinned } from "@/lib/ceremony-state";
import { esc, LIVE } from "@/lib/esigncomply";

const SEALED = ["recorded", "timestamped", "anchored"];

export async function POST(request: Request) {
  const { recordId } = await request.json();
  const pinned = await loadPinned();
  const { data: record, error } = await esc.records.get(String(recordId));
  if (error || !pinned) return Response.json({ confirmed: false }, { status: 409 });

  const confirmed =
    SEALED.includes(record.status) &&
    record.livemode === LIVE &&
    record.signer.external_id === pinned.signerId &&
    JSON.stringify(record.documents.map((d) => d.version_id).sort()) === JSON.stringify([...pinned.versionIds].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 dev server prints one line for each confirmation:

```text
confirmed rec_BLxiMko5JhhErbxqtVmK (recorded)
```

Three requests that must be refused were tried against this code, and each one answered `409` with `{"confirmed":false}`: a sealed record ID sent with no cookie, the same ID sent with a cookie whose payload had been changed, and a test record while `VERCEL_ENV` was `production`.

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

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

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, 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_s6u4GbFy6qt3EukGPphE  session ses_NWVxRXYNifs9TNF9h6JJ, 5 events
  768x1024   record rec_4k6jrJec83ECbPxViDt8  session ses_EWgid2EjFmCZmudfcyx2, 5 events
  1440x900   record rec_JY2f93ZvkN0veL6jq8u0  session ses_S0Qfs7QUxCwf0PmLEyx8, 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 Vercel project. The settings below are from Vercel's own documentation, checked on November 23, 2026: [Environment variables](https://vercel.com/docs/environment-variables), [System environment variables](https://vercel.com/docs/environment-variables/system-environment-variables), [vercel env](https://vercel.com/docs/cli/env) and [Generated URLs](https://vercel.com/docs/deployments/generated-urls).

**Environment Variables.** Add each variable in the project's settings under Environment Variables, or with the CLI. Changes apply to new deployments only, so redeploy after you add or change one.

```bash
# The test key and the test IDs: Preview and Development.
vercel env add ESIGNCOMPLY_API_KEY --environment preview --sensitive
vercel env add ESIGNCOMPLY_API_KEY --environment development --sensitive
# The live key and the live IDs: Production only.
vercel env add ESIGNCOMPLY_API_KEY --environment production --sensitive
# The cookie secret, in every environment.
vercel env add CEREMONY_STATE_SECRET --environment production,preview,development --sensitive
```

Add `ESIGNCOMPLY_PROFILE_ID`, `ESIGNCOMPLY_TERMS_ID` and `ESIGNCOMPLY_PRIVACY_ID` the same way: the test IDs for Preview and Development, the live IDs for Production. `vercel env pull` writes the Development values to `.env.local`. Keep "Enable access to System Environment Variables" on in the same settings page: `VERCEL_ENV` comes from it.

**Preview deployments.** Every preview runs on its own `vercel.app` host, and a test key refuses a host it does not know with [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch). Vercel gives each Git branch a stable address, `<project-name>-git-<branch-name>-<scope-slug>.vercel.app`, which keeps pointing at the branch's latest deployment. List that host under Domains in the dashboard, or with the API, and open previews through it:

```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": ["my-app-git-main-acme.vercel.app"] }'
```

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

**The production domain.** Register your custom domain and verify it with one DNS record. If production runs on a `vercel.app` host, you cannot add DNS records there, so the domain verifies with a file instead. A Route Handler serves the token from an Environment Variable and keeps it out of the repository:

```ts file="app/.well-known/esigncomply.txt/route.ts"
// app/.well-known/esigncomply.txt/route.ts
// Verifies a *.vercel.app host by file. The token stays in an environment variable, out of the repository.
export function GET() {
  return new Response(process.env.ESIGNCOMPLY_DOMAIN_TOKEN ?? "", {
    headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" },
  });
}
```

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

- **`domain_mismatch` on a preview deployment.** The preview's host is not a test origin of your domain. In a local test, a session requested from `https://myapp-git-main-acme.vercel.app` was refused with this code, and accepted once that host was listed. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch) and [Test mode](https://esigncomply.com/docs/guides/test-mode.md).
- **The confirm route answers `409` on a preview.** Either the cookie did not come back, or the code compares `livemode` with `NODE_ENV`. A preview deployment has `NODE_ENV` set to `production` and holds the test key, so only `VERCEL_ENV` tells it from production. A record ID that does not exist fails the same way, with [`not_found`](https://esigncomply.com/docs/api/errors.md#not_found).
- **`missing_api_key` after adding the variable.** Environment Variables apply to new deployments only. Redeploy, and check that the variable is applied to the environment the deployment runs in. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`429` when the confirm route reads the record.** The Route Handler 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 cookie of the session that made it, all answered `200`, two of them over half a second later than the others. Four reads sent at once through the package 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 Vercel quickstart

### Which key goes in which Vercel environment?

The test key goes in Preview and Development, and the live key in Production only. Vercel applies each Environment Variable to the environments you select, so the same name, `ESIGNCOMPLY_API_KEY`, holds a different key in each one.

### How does test mode work on Vercel preview URLs?

A test key works on a preview once its host is listed as a test origin of your domain. Vercel gives each Git branch a stable address that ends in `vercel.app`, so list that one and open previews through it. Without the entry, the session is refused with `domain_mismatch`.

### Why does the quickstart use VERCEL_ENV and not NODE_ENV?

Because a preview deployment is a production build. `NODE_ENV` is `production` there, while the key is a test key and the records are test records. `VERCEL_ENV` is `production` only on the production deployment, which is the one place a live record is expected.

### Why is the pinned state in a signed cookie?

Because two requests on Vercel can run in two function instances that share no memory. The cookie is httpOnly and signed with `CEREMONY_STATE_SECRET`, so the browser carries it and cannot change it. A table in your database does the same job.

### Was this quickstart run on a Vercel deployment?

Not yet. The code was run on `localhost` with Next.js 16.4.6 and `VERCEL_ENV` set by hand, and the Vercel settings come from Vercel's documentation as of November 23, 2026. Environment scoping, the function runtime and file verification on a `vercel.app` host are proven only by a deployment.

## Next steps

- [E-signatures and clickwrap on Vercel](https://esigncomply.com/vercel): how the pieces fit on this platform, with the things to watch for.
- [Add e-signatures and clickwrap with Next.js](https://esigncomply.com/docs/quickstart/nextjs.md): the session in a Server Component, without the Vercel parts.
- [Register a domain](https://esigncomply.com/docs/guides/domains.md): DNS and file verification, statuses, and test origins.
- [Next.js guide](https://esigncomply.com/docs/guides/nextjs.md): the full application with a Supabase table, the webhook and the re-acceptance gate.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
