Skip to content

Cookbook

Cancel stale envelopes automatically

Envelopes have no expiry setting, so run a scheduled job that cancels the ones still in progress after a set number of days and records the reason.

An envelope stays in_progress until every recipient finishes or you cancel it. To set a deadline, run a daily job that cancels envelopes older than your limit.

Node.js
const API = "https://api.signatureapi.com/v1";
const headers = { "X-API-Key": process.env.SIGNATUREAPI_KEY, "Content-Type": "application/json" };
const MAX_AGE_DAYS = 30;

export async function cancelStale() {
  const cutoff = Date.now() - MAX_AGE_DAYS * 24 * 60 * 60 * 1000;
  let url = `${API}/envelopes?status=in_progress&limit=20`;

  while (url) {
    const page = await (await fetch(url, { headers })).json();

    for (const envelope of page.data) {
      if (Date.parse(envelope.created_at) > cutoff) continue;

      const res = await fetch(`${API}/envelopes/${envelope.id}/cancel`, {
        method: "POST",
        headers,
        body: JSON.stringify({ reason: `Not signed within ${MAX_AGE_DAYS} days` }),
      });
      // 409: it completed or was canceled since the list was read. Nothing to do.
      if (!res.ok && res.status !== 409) console.error(envelope.id, res.status);
    }
    url = page.links.next;
  }
}
Python
import os
from datetime import datetime, timedelta, timezone

import requests

API = "https://api.signatureapi.com/v1"
HEADERS = {"X-API-Key": os.environ["SIGNATUREAPI_KEY"]}
MAX_AGE_DAYS = 30


def cancel_stale():
    cutoff = datetime.now(timezone.utc) - timedelta(days=MAX_AGE_DAYS)
    url = f"{API}/envelopes?status=in_progress&limit=20"

    while url:
        page = requests.get(url, headers=HEADERS).json()

        for envelope in page["data"]:
            created = datetime.fromisoformat(envelope["created_at"].replace("Z", "+00:00"))
            if created > cutoff:
                continue

            res = requests.post(
                f"{API}/envelopes/{envelope['id']}/cancel",
                headers=HEADERS,
                json={"reason": f"Not signed within {MAX_AGE_DAYS} days"},
            )
            # 409: it completed or was canceled since the list was read. Nothing to do.
            if not res.ok and res.status_code != 409:
                print(envelope["id"], res.status_code)

        url = page["links"]["next"]
  • Only in_progress can be canceled. An envelope still processing returns 409 cannot-cancel, and the job picks it up on the next run.
  • Cancel is permanent. Recipients lose access to their ceremonies, and it can’t be undone. To warn people first, send reminders before the cutoff.
  • The reason is for you. It isn’t shown to recipients. It is returned in the envelope.canceled event as data.reason, so your system can tell an expiry from a manual cancel.
  • Scoped cancels. To expire only some envelopes, give them a topic and add &topic=contracts to the list URL.