Skip to content
Pattern · consent withdrawal

Build consent withdrawal into your own app

To build consent withdrawal into your own app, record each consent as its own sealed record, then report the withdrawal from your server when the person opts out in your settings. Esign Comply attaches a timestamped withdrawal to that record and notifies your webhook. The earlier record stays as it is, and stopping the messages is your app's job.

Read the prompt

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

Last updated

POST /v1/sessions · test mode
curl https://esigncomply.com/v1/sessions \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: consent-user_7c1d-marketing_email" \
  -d @- <<JSON
{
  "profile": "$ESC_PROFILE_ID",
  "signer": {
    "external_id": "user_7c1d",
    "email": "dana@example.org",
    "class": "consumer",
    "country": "US"
  },
  "documents": [
    {
      "document": "$ESC_MARKETING_CONSENT_DOCUMENT_ID",
      "version": "current"
    }
  ],
  "context": {
    "url": "http://localhost:3000/settings/notifications",
    "locale": "en-US",
    "purpose": "other"
  }
}
JSON
The prompt · from the generator

Which prompt builds consent withdrawal in your AI coding tool?

The Esign Comply prompt generator produced this for marketing or data consent with a Marketing Consent document, on Next.js App Router with Supabase and Vercel, under the U.S. Federal rule pack. Paste it into Cursor, Claude Code, v0, Lovable, Bolt or Replit. Your tool builds the opt-in, the acceptances table, the server confirmation and the webhook.

A withdrawal needs a consent to withdraw, so this page maps to the generator's marketing or data consent use case, which builds the opt-in. The withdrawal itself is one server call, shown in the code below. IDs in angle brackets are placeholders the prompt tells your tool to ask for, and {Company} is your company name.

Generate it for your own regions and stack
esigncomply-consent-withdrawal-prompt.md · 1,638 words
# Esign Comply integration: marketing consent
Prompt esc_prompt_b5e46b145e7a · blocks 2026.11 · guidance bundled · region US
Jurisdictions: US-FED · mode auto

You are adding legally significant acceptance flows to this Next.js App Router application (TypeScript, Supabase Auth and Postgres, deployed on Vercel). Esign Comply is the independent record keeper. You build every screen. The Esign Comply SDK observes the screens you build and seals the record.

Follow this prompt exactly. If something here 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.

This prompt has four kinds of instruction. Keep them apart:
- "Required for the record": build all of it. Esign Comply checks these.
- "Your obligations": duties the law places on {Company}. Esign Comply does not check them. Build what code can do and list the rest in your report.
- "Recommendations": suggestions. Ask the developer before applying any that changes the product.
- "What you can send us": optional reports {Company} may file with Esign Comply.

## Context
- Packages (the only ones that exist): `esigncomply` (server), `@esigncomply/browser` (client), `@esigncomply/react` (optional hooks).
- API host: https://esigncomply.com/v1
- Environment variables (server only, never NEXT_PUBLIC_): ESIGNCOMPLY_API_KEY, ESIGNCOMPLY_WEBHOOK_SECRET
- Profiles: marketing consent = `<profile ID for marketing consent>`
- Documents: Marketing Consent = `<document ID for Marketing Consent>`
- An ID in angle brackets does not exist yet. Ask the developer for it. Do not invent IDs.
- Rule pack versions: 2026-11-22 (all selected packs).
- Server SDK calls return `{ data, error }` and do not throw. Check `error` every time.

## Required for the record
1. Create every session on the server with the secret key. Send only `client_token` to the browser.
2. Read `required_steps` and `advised_steps` from the session and satisfy every one. Do not hard-code steps.
3. Show the notice text directly above the action button, in the same container, visible without scrolling at 390 x 844 (CR-04).
4. Notice wording for marketing consent, verbatim, with links:
   "By checking the box and clicking Confirm, you agree to the [Marketing Consent]." (CR-02, CR-03)
5. Links to documents must be underlined and use a colour that differs from the surrounding text with a contrast ratio of at least 3:1, and at least 4.5:1 against the background. Notice text is at least 14px and never lighter than body text (CR-05, CR-06).
6. Every checkbox starts unchecked (CR-01).
7. Only one primary button inside the assent container. Any other action sits outside it (CR-07).
8. Serve each document at a stable page on this domain that renders the registered version fetched from Esign Comply, unmodified (CR-08).
9. Treat the browser result as untrusted. Grant access only after the server has confirmed the record with the secret key (step 5 below).
10. Pass an `Idempotency-Key` on session creation.

### Never
- Never pre-check a box, auto-submit, or call `.click()` on the user's behalf.
- Never treat sign-in, scrolling, or continued use as acceptance.
- Never use "By continuing" or "By clicking below" wording.
- Never put the secret key, or any call that uses it, in a client component.
- Never proxy `@esigncomply/browser` calls through this application's server.
- Never cache or copy document text into the repository. Always render the registered version.
- Never write to `esign_acceptances` from the browser.
- Never show "signed" or "accepted" in the interface before step 5 confirms it.
- Never write or change the text of the Marketing Consent.

## Your obligations
These are {Company}'s duties under the rule packs selected. Esign Comply lists them and does not perform, monitor, or verify them. The list is not exhaustive.

US-FED · pack 2026-11-22
- Customer: where another law requires {Company} to keep a record, keep an accurate, accessible copy for that period, including after export (US-31); before offering a record in court, give the adverse party reasonable written notice and access to the record and declaration (US-38). Outside this codebase.

## Recommendations
Esign Comply recommends the following. Ask the developer which to apply.

- Give the signer a clear way to decline (US-04).
- Before a material update to a document takes effect, notify signers in advance and ask for a fresh acceptance (US-18).
- Keep saving and printing open wherever a signed record is shown (US-29).
- Where minors may sign, consider an age attestation checkbox: `ceremony.ageAttested({ checkbox })` (US-42).

## What you can send us
Optional. Each report is sealed with Esign Comply's receipt time and marked as supplied by {Company}; Esign Comply does not verify it. Every field is optional and any text, JSON, or file is accepted.
Reports never affect recording, and a failed one never blocks the user's action. Suggested `data` per type: `esc.supplements.types()`.

- When the terms-update notice email is sent:
  `esc.supplements.create({ subject: { signer: signerId }, type: "notice.sent", rule_ids: ["US-18"], text, data: { channel: "email", template } })`
- Anything else worth keeping (support ticket, screenshot, policy in force): type `note`, or omit `type`.

Only wire these if the developer says yes.

## Build steps

### 1. Install and configure
`npm install esigncomply @esigncomply/browser`
Create `lib/esigncomply.ts`:
```ts
import "server-only";
import { EsignComply } from "esigncomply";
export const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!);
```
Keys go in `.env.local` and the Vercel project settings, never in chat.
Run commands in the integrated terminal. Rules file: `.cursor/rules/esigncomply.mdc`.

### 2. Database (Supabase migration)
```sql
create table public.esign_acceptances (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references auth.users(id) on delete cascade,
  signer_id uuid not null,
  record_id text not null unique,
  document_id text not null,
  version_id text not null,
  purpose text not null,
  signed_at timestamptz not null,
  created_at timestamptz not null default now()
);
alter table public.esign_acceptances enable row level security;
create policy "read own" on public.esign_acceptances
  for select using (auth.uid() = user_id);
-- No insert, update, or delete policies. Only the service role writes.
```
Add `signer_id uuid unique` to the profile table.

### 3. Document pages
Create `app/legal/[slug]/page.tsx` for `marketing-consent`. Resolve `current` on session creation only. Fetch with `esc.documents.versions.getContent(documentId, versionId)`; render, print and download by the exact version ID returned on the session; the cache key includes that ID. Render inside `<article data-esc-document>` and reject stale versions before the final action. Give users a real opportunity to read the terms.

### 4. Marketing consent ceremony (`/consent/marketing`)
Server action `startMarketingConsentCeremony()`:
- `signerId` is the signed-in user's `signer_id`; create and store one with `crypto.randomUUID()` if it is missing. Never accept it from the browser. `attemptId` is a UUID made when the page first renders and reused on retry.
- Call:
```ts
const { data, error } = await esc.sessions.create({
  profile: "<profile ID for marketing consent>",
  signer: { external_id: signerId, email, class: "consumer", country, region },
  documents: [
    { document: "<document ID for Marketing Consent>", version: "current" },
  ],
  context: { url: `${origin}/consent/marketing`, locale, purpose: "other" },
}, { idempotencyKey: `marketing-${attemptId}` });
```
- Obtain `country` and applicable jurisdiction from the form/customer configuration; do not guess from IP. `region`: the U.S. state as an ISO code ("US-NY"), if collected.
- Return `data.client_token` and `data.documents` to the client.

Client component `MarketingConsentForm`:
```tsx
"use client";
import { EsignComply } from "@esigncomply/browser";
// after the server action returns clientToken:
const ceremony = await EsignComply.attach({ clientToken });
await ceremony.presentDocument({ versionId: marketingConsentVersionId, mode: "hyperlink", link: marketingConsentLinkRef.current });
ceremony.observeAssent({
  region: assentRef.current,    // contains notice, links, checkbox, button
  checkbox: checkboxRef.current,
  submit: submitRef.current,
});
// in the submit handler, from the user's real click:
try {
  const result = await ceremony.complete();                  // { recordId, receipt, verifyUrl }
  await finishMarketingConsent(formData, result.recordId);   // server action, step 5
} catch (err) {
  showError(err.message);                                    // typed error with rule ID
}
```
Disable the button until `ceremony.remainingSteps()` contains only "signature.applied".
Start the ceremony when the page renders, not on submit.

### 5. Server confirmation (the only place access is granted)
Server action `finishMarketingConsent(formData, recordId)`:
- `const { data: record, error } = await esc.records.get(recordId);`
- Require: no error; `record.status` is "recorded", "timestamped", or "anchored"; `record.signer.external_id` equals the signed-in user's `signer_id`; `record.livemode` equals `process.env.VERCEL_ENV === "production"`; the record lists the exact versions pinned in that session.
- Only then record the marketing preference, and insert one `esign_acceptances` row per document using the service-role client.
- If checks are inconclusive, do not record the marketing preference. Show: "We could not confirm whether your acceptance was recorded. Please wait while we check." Reconcile the existing session before requesting another act.

### 6. Webhook
`app/api/esigncomply/webhook/route.ts`, Node.js runtime. Read the raw body, then `esc.webhooks.verify(rawBody, request.headers, process.env.ESIGNCOMPLY_WEBHOOK_SECRET!)`.
Reject on failure with 400. Handle idempotently by `webhook-id`:
- `record.completed`: upsert `esign_acceptances` (covers a browser that closed early).
- `record.disputed`: flag the row and notify the admin email.
- Ignore event types you do not recognise and return 200.
Return 200 within 5 seconds.

### 7. Errors
- `ceremony.complete()` rejected with a rule ID: show the message, keep the form, do not retry automatically.
- Network failure or 5xx: show "We could not confirm whether your acceptance was recorded. Please wait while we check." Reconcile the same session and idempotency key before requesting another act. Never proceed without a record.
- `client_token_expired`: create a new session and re-attach.

## Verify before you report success
1. `npm run build` passes and no file under `app/**` marked "use client" imports `esigncomply` or reads ESIGNCOMPLY_API_KEY.
2. Run `npx esigncomply check --url http://localhost:3000/consent/marketing`. Fix every finding marked "block", re-running until none is left. List every finding marked "warn" in your report.
3. Confirm by test that submitting with the box unchecked does nothing, and that calling `finishMarketingConsent` with a made-up record ID does not record the marketing preference.
4. Report: files created or changed, anything in this prompt you did not implement and why, the conformance summary, each item under "Your obligations" with "built", "partly built", or "needs a process outside this codebase", and each recommendation with the developer's decision.

5 required steps

Which steps does Esign Comply require for a consent a person can withdraw?

The consent comes first. A session created with the recommended consent profile returns these five required_steps. The withdrawal, later, is a server call and has no steps.

Esign Comply's guidance for consent withdrawal

A consent of its own, so it can be withdrawn on its own

Esign Comply recommends a separate checkbox, button and record for each consent, at level L1. A consent that is bundled into your terms cannot be withdrawn without touching the terms. A consent with its own record can: the withdrawal attaches to that record and nothing else changes.

  • Document typeconsent
  • MethodCheckbox and button
  • LevelL1, no identity step
  • method: checkboxassurance_level: L1purpose: other
  1. 01

    The SDK attaches to your opt-in

    client.attached
    The signer sees

    Your opt-in, in notification settings or at the end of sign-up.

    Esign Comply records

    The page address, the SDK version, the viewport, the browser language and the time zone, reported from the signer's browser.

  2. 02

    The consent text is linked

    document.presented:<version_id>
    The signer sees

    An underlined link to your Marketing Consent page, which says what you send, how often and how to stop.

    Esign Comply records

    The pinned version ID, the link text and address, how the link looked on the page, and whether the signer opened it.

  3. 03

    The notice is captured

    notice.captured
    The signer sees

    The notice directly above the button: "By checking the box and clicking Confirm, you agree to the Marketing Consent."

    Esign Comply records

    The visible text of the assent area, the checkbox label and its unchecked starting state, the button label, the document links and the layout measurements.

  4. 04

    The person ticks the box

    intent.captured
    The signer sees

    An unchecked box labelled with what they agree to receive.

    Esign Comply records

    The tick, the label text, the box's starting state, and whether a real user event changed it. An untick is recorded too.

  5. 05

    The consent is given

    signature.applied
    The signer sees

    The Confirm button. The same settings page later carries the control that withdraws it.

    Esign Comply records

    The final act with Esign Comply's server time. The API seals the record and returns a signed receipt.

Keep the record ID of the consent on the user's row. It is what the withdrawal names, so that it attaches to this consent and not to the person's latest record of another kind.

Code · run before publishing

How do you record a consent a person can withdraw with the Esign Comply API?

Consent withdrawal takes four pieces of code: the consent text and the profile you register once, the session and the ceremony that record the opt-in, and the server call that records the opt-out.

import { EsignComply } from "esigncomply";

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

export async function startConsentSession(origin: string, user: { signerId: string; email: string }) {
  const { data: session, error } = await esc.sessions.create(
    {
      profile: process.env.ESC_PROFILE_ID!,
      signer: { external_id: user.signerId, email: user.email, class: "consumer", country: "US" },
      documents: [{ document: process.env.ESC_MARKETING_CONSENT_DOCUMENT_ID!, version: "current" }],
      context: { url: `${origin}/settings/notifications`, locale: "en-US", purpose: "other" },
    },
    { idempotencyKey: `consent-${user.signerId}-marketing_email` },
  );
  if (error) throw new Error(`${error.code}: ${error.message}`);
  // Only the client token, the API base for it and the pinned versions go to the browser.
  return { clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents };
}
Which record a withdrawal lands on

One detail of this flow

Without record_id, a withdrawal attaches to the signer's latest record in which consent to electronic records was given, and otherwise to their latest record, with the scope electronic_records. For a marketing consent, pass the record ID of that consent and a scope of your own, up to 64 characters. The withdrawal is then a consent_withdrawn annotation on exactly that record.

How the four files fit

Register once, then one session per signer

Store recordId with the consent when your server confirms it. Stop sending as soon as the person opts out, then report the withdrawal: the order matters to the person, not to the API.

session.ts reads the profile from ESC_PROFILE_ID and the document from ESC_MARKETING_CONSENT_DOCUMENT_ID: the IDs register.ts returned. Every sample is run as printed against the API in test mode, and ceremony.ts in a real browser.

withdraw.ts runs on your server when the person switches the consent off. It needs a key with full_access permission.

You vibe code · Esign Comply handles

What do you build for consent withdrawal, and what does Esign Comply handle?

The switch in your settings and what happens after it are yours. Esign Comply keeps the two facts a regulator or a court asks for: when consent was given, and when it was withdrawn.

The consent

You vibe code

An opt-in with its own unchecked box and button, apart from your terms.

Esign Comply handles

A sealed record of that one consent: the text, the box, the tick and the time.

The opt-out control

You vibe code

A switch or a link that is as easy to use as the opt-in was.

Esign Comply handles

Nothing on the screen. The withdrawal is reported by your server.

Recording the withdrawal

You vibe code

One call to esc.signers.withdrawConsent() with the consent's record ID and the scope.

Esign Comply handles

A timestamped consent_withdrawn annotation with its own ledger entry, and the consent.withdrawn webhook.

Afterwards

You vibe code

Stop the messages, or switch the person to paper, and report what you did if you want it on file.

Esign Comply handles

Seals what you report as a supplement, marked as supplied by you.

The record

What does the Esign Comply record of a consent a person can withdraw show?

A withdrawal does not rewrite the consent. The record keeps its status and its seal, and gains an annotation that says the consent was withdrawn, by whom it was reported and when.

observed

Observed by Esign Comply

  • The exact version of the consent text, pinned by its SHA-256 hash.
  • The checkbox label, its unchecked starting state and the person's own tick, with whether a real user event made it.
  • The notice text and the button label as the browser rendered them, with the layout measurements.
  • The withdrawal as a consent_withdrawn annotation: who reported it, when Esign Comply received it, and its own ledger entry.
  • Esign Comply's server time for every step, in order.
  • A receipt signed with ES256 keys you do not hold, an RFC 3161 timestamp from an outside authority, and an entry in a hash-chained ledger.
asserted

Asserted by your app

  • The person's ID and email, as your server passed them.
  • The scope and the note on the withdrawal: your own words for what was withdrawn.
  • The page address in context.url, the purpose, and anything you put in metadata.

Your server supplies these, and the record marks them as supplied by you. Esign Comply stores them and does not verify them.

  • Signed receiptStore it in your consents tablecomplete() returns the receipt in the browser, and your server reads the record again with esc.records.get(recordId). Save the record ID and the receipt on the row.
  • PDF, per recordEvidence reportGET /v1/records/{id}/report shows the consent text and its hash, the checkbox label, the notice, the timeline of the consent, and the annotations added since.
  • verify_urlVerification pageEvery record has a public verification page. With an email on the session and receipts on, Esign Comply also sends the person a copy with that link.
  • ZIP, verifies offlineEvidence packageThe record, the receipt, the timestamp token, the ledger proof and the exact document bytes. Anyone you hand it to runs the open-source esigncomply-verify with no account and no network.
Your obligations · from the generator

What are your obligations when you collect a consent a person can withdraw?

Honouring a withdrawal is your duty, and no API call performs it. For the signing flow, the U.S. Federal rule pack places these duties on your company, in the prompt generator's words. Esign Comply lists them, and your team carries them out.

US-FED · pack 2026-11-22
  • Customer: where another law requires your company to keep a record, keep an accurate, accessible copy for that period, including after export (US-31); before offering a record in court, give the adverse party reasonable written notice and access to the record and declaration (US-38). Outside this codebase.

Each line names who owes the duty and the rule it comes from, and ends with what the prompt tells your AI tool to build. "Outside this codebase" marks a duty that no code performs: it is a process your team runs. An obligation never blocks a session and never adds a step. How rules are split into classes.

Rule packs

Which rule packs change how you collect a consent a person can withdraw?

Withdrawal applies to every pack the same way: it is prospective, and the earlier record remains. The packs differ on the consent itself. The U.S. Federal pack carries the consumer consent rules of the E-SIGN Act, and the Florida pack adds its telephone marketing rule when the consent covers calls or texts.

Rule packs, their versions, how many of their rules apply to a consent a person can withdraw, and the rules to know for this flow
Rule packPack versionRules that applyRules to know for this flow
United States, FederalUS-FED2026-11-2233US-04 Agreement to transact electronicallyUS-05 Review step before the final act
CaliforniaUS-CA2026-11-211The pack's general rules
New YorkUS-NY2026-11-211The pack's general rules
FloridaUS-FL2026-11-213FL-06 Telemarketing written consent
TexasUS-TX2026-11-215The pack's general rules
DelawareUS-DE2026-11-211The pack's general rules
VirginiaUS-VA2026-11-211The pack's general rules
MassachusettsUS-MA2026-11-214The pack's general rules
European Union and EEAEU2026-11-2120The pack's general rules
United KingdomUK2026-11-2118The pack's general rules
SwitzerlandCH2026-11-219The pack's general rules

The counts are the rules the prompt generator resolves for this flow when a pack is selected. The prompt on this page is generated for United States, Federal (US-FED). Enable more packs on the profile, send the signer's country and state on the session, and the API applies the packs that cover that signer and returns the rules that fired. United States, Europe, jurisdictions guide.

Limits

When is a consent a person can withdraw blocked or flagged?

Any consent recorded through the API can be withdrawn. These are the limits of what a withdrawal does.

  • By design

    Withdrawal is prospective

    A withdrawal is an annotation on the record. The consent, its seal and its timeline stay as they were, and what you did while the consent stood is not undone.

  • By design

    Stopping is your job

    Esign Comply records the withdrawal and sends the webhook. Taking the person off the list, or switching them to paper delivery, is your responsibility.

  • By design

    A withdrawal needs a record

    A signer with no record has nothing to attach a withdrawal to, and the call answers 404. A record_id that belongs to another signer is refused the same way.

  • By design

    The scope is your label

    scope is free text of up to 64 characters. Esign Comply stores it and does not interpret it, so use one fixed value for each kind of consent.

Consent withdrawal in your own app: questions developers ask

How do I record that a user withdrew their consent?

Call POST /v1/signers/{external_id}/consents/withdraw from your server with the record ID of the consent and a scope. Esign Comply adds a timestamped consent_withdrawn annotation to that record and sends the consent.withdrawn webhook.

Signers API

Does a withdrawal delete the original consent record?

No. Withdrawal is prospective only. The consent record keeps its status and its seal, and the annotation shows when the consent ended.

Can a person withdraw without going through my app?

Yes, for consent to electronic records: every receipt Esign Comply emails carries a link to withdraw it. Your server learns of it through the consent.withdrawn webhook. For other consents, the control is the one you build.

Consent to electronic records

What do I have to do after a withdrawal?

Stop relying on the consent: take the person off the list, or switch them to paper delivery. Esign Comply does not do this for you. You can report what you did as a supplement, which is sealed as material you supplied.

Supplements API

How do I test the withdrawal path?

Call the endpoint with a test key against a test record. To test the signer's own route, create a test session for signer+withdraw@test.esigncomply.com: a withdrawal is filed 10 seconds after the record is sealed.

Test mode

Why keep consent apart from my terms of service?

Because a person can withdraw a consent and keep the account. With its own checkbox, button and record, a consent can end without touching the terms the person accepted.

Marketing consent

Build consent withdrawal yourself. Leave the record to us.

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

Docusign, Cursor and the other product names on this page are trademarks of their owners. Esign Comply is not affiliated with them.

Working with an AI tool? This page is also available as Markdown: /use-cases/consent-withdrawal.md