documenso-pack
Complete Documenso integration skill pack with 24 skills covering document signing, templates, workflows, and e-signature automation. Flagship tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install documenso-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> Claude Code skill pack for Documenso integration — open-source document signing (24 skills)
Skills (24) plugin-local skills
Configure CI/CD pipelines for Documenso integrations.
Documenso CI Integration
Output
- A credential-free pull-request lane for schema/template/unit checks and a trusted, scoped development integration lane.
- A redacted CI receipt with validation outcome and a safe failure/retry procedure.
Examples
Run template/schema/unit checks on every pull request using synthetic documents and signers, then execute one protected-branch development integration check with a scoped secret. If it fails, retain redacted correlation/status evidence; never expose signing credentials, document payloads, or production workspace access to forked CI code.
Overview
Configure CI/CD pipelines for Documenso integrations with GitHub Actions. Covers unit testing with mocks, integration testing against staging, and deployment workflows with secret management.
Prerequisites
- GitHub repository with Actions enabled
- Documenso staging API key
- Test environment configured (see
documenso-local-dev-loop)
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/documenso-ci.yml
name: Documenso CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
NODE_ENV: test
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test
# Unit tests use mocks — no API key needed
integration-tests:
runs-on: ubuntu-latest
if: github.event_name == 'push' # Only on push to main/develop
needs: unit-tests
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run test:integration
env:
DOCUMENSO_API_KEY: ${{ secrets.DOCUMENSO_STAGING_API_KEY }}
- run: npm run test:cleanup # Remove test documents
env:
DOCUMENSO_API_KEY: ${{ secrets.DOCUMENSO_STAGING_API_KEY }}
if: always()
Step 2: Unit Tests with Mocked SDK
// tests/unit/document-service.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";
import { createMockClient } from "../mocks/documenso";
import { DocumentService } from "../../src/services/document-service";
describe("DocumentService", () => {
let service: DocumentService;
let mockClient: ReturnType<typeof createMockClient>;
beforeEach(() => {
mockClient = createMockClient();
service = new DocumentService(mockClient as any);
});
it("creates document with recipients and sends", async () => {
const result = await service.createAndSend({
title: "Test CoDiagnose and resolve common Documenso API errors and issues.
Documenso Common Errors
Output
- A classified document/signing integration failure with redacted evidence and a bounded remediation or escalation.
- A verified recovery that preserves authorization, document integrity, signing lifecycle, and audit continuity.
Examples
For a failed signing action, record the opaque document/correlation ID, environment, lifecycle state, status class, and timestamp. Verify signer role, expiration, callback, and authorization with a synthetic fixture; escalate with redacted evidence if unresolved, rather than sharing the document or signing link.
Overview
Quick-reference troubleshooting guide for Documenso API errors. Covers authentication, document lifecycle, field validation, file upload, webhook, and SDK-specific issues with concrete solutions.
Prerequisites
- Working Documenso integration (see
documenso-install-auth) - Access to application logs
- API key available
HTTP Error Reference
| Status | Error | Cause | Solution |
|---|---|---|---|
| 401 | Unauthorized | Invalid, expired, or missing API key | Regenerate key in dashboard; verify Authorization: Bearer <key> header |
| 403 | Forbidden | Personal key accessing team resources | Use a team-scoped API token |
| 404 | Not Found | Wrong document/template ID or deleted resource | Verify ID with GET /api/v1/documents |
| 400 | Bad Request | Invalid payload or missing required fields | Check request body against API spec |
| 413 | Payload Too Large | PDF exceeds upload limit | Compress PDF; cloud plan limit varies by tier |
| 429 | Too Many Requests | Rate limit exceeded | Implement backoff; see documenso-rate-limits |
| 500/502/503 | Server Error | Documenso infrastructure issue | Retry with exponential backoff; check status.documenso.com |
Instructions
Scenario 1: 401 Unauthorized
// WRONG: missing or malformed header
const res = await fetch("https://app.documenso.com/api/v1/documents", {
headers: { "Authorization": process.env.DOCUMENSO_API_KEY! }, // Missing "Bearer "
});
// CORRECT: include Bearer prefix
const res = await fetch("https://app.documenso.com/api/v1/documents", {
headers: { "Authorization": `Bearer ${process.env.DOCUMENSO_API_KEY}` },
});
// SDK handles this automatically:
import { Documenso } from "@documenso/sdk-typescript";
const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEImplement Documenso document creation and recipient management workflows.
Documenso Core Workflow A: Document Creation & Recipients
Output
- A role-limited document/recipient workflow with validated metadata, lifecycle, authorization, and redacted audit result.
- A safe disable/rollback path for an incorrect recipient, permission, or state transition.
Examples
Create a synthetic development document, assign a test recipient with the minimum required role, verify expiration/authentication/callback behavior, and archive it after the check. If role or recipient behavior is wrong, disable the workflow and correct it before promotion; do not substitute a real signer for the test.
Overview
Complete workflow for creating documents, managing recipients with different roles, positioning fields, and controlling signing order. Covers both the SDK and v1 REST API for document-centric operations.
Prerequisites
- Completed
documenso-install-authsetup - Understanding of
documenso-sdk-patterns - PDF file ready for signing
Instructions
Step 1: Create a Document with the SDK
import { Documenso } from "@documenso/sdk-typescript";
import { readFileSync } from "fs";
const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
// Create document shell
const doc = await client.documents.createV0({
title: "Service Agreement — Q1 2026",
});
// Upload PDF
const pdf = readFileSync("./contracts/service-agreement.pdf");
await client.documents.setFileV0(doc.documentId, {
file: new Blob([pdf], { type: "application/pdf" }),
});
Step 2: Recipient Roles
Documenso supports these recipient roles:
| Role | Behavior |
|---|---|
SIGNER |
Must complete all assigned fields to finish |
VIEWER |
Receives a copy but takes no action |
APPROVER |
Must approve before signers can proceed |
CC |
Receives a completed copy after all signatures |
// Add multiple recipients with roles
const signer = await client.documentsRecipients.createV0(doc.documentId, {
email: "ceo@acme.com",
name: "Alice CEO",
role: "SIGNER",
});
const approver = await client.documentsRecipients.createV0(doc.documentId, {
email: "legal@acme.com",
name: "Legal Team",
role: "APPROVER",
});
const cc = await client.documentsRecipients.createV0(doc.documentId, {
email: "records@acme.com",
name: "Records",
role: "CC",
});
Step 3: Signing Order
Control the sequence in which recipients act. Lower numbers go first.
documenso-core-workflow-b
View full skill →
Implement Documenso template-based workflows and direct signing links.
ReadWriteEdit
Documenso Core Workflow B: Templates & Direct Signing
Output
- A reviewed template/direct-signing workflow with role-limited access, lifecycle validation, and a safe disable/rollback action.
- A redacted receipt showing environment, document/template version, state transitions, and result.
Examples
Create a development template with synthetic fields and signer, verify role order, expiration, authentication, signing state, and callback behavior, then disable/archive the test document. Do not use real agreements or signer identity for the walkthrough, and stop promotion if authorization or lifecycle state differs from the review.
Overview
Create reusable templates, generate documents from templates with prefilled fields, and implement direct signing links for public/anonymous signers. Templates define the PDF, fields, and recipient roles once — then stamp out documents on demand.
Prerequisites
- Completed
documenso-core-workflow-a
- At least one PDF uploaded to Documenso as a template
- Understanding of recipient roles and field types
Instructions
Step 1: Create a Template via Dashboard
Templates are created in the Documenso UI:
- Navigate to Templates in the sidebar.
- Click Create Template and upload a PDF.
- Add placeholder recipients (e.g., "Signer 1", "Approver") — these become roles that get filled when creating documents from the template.
- Place fields on the PDF and assign them to placeholder recipients.
- Save the template and note the template ID from the URL.
Step 2: Create Document from Template (v1 REST API)
// The v1 API has a dedicated template endpoint
const templateId = 42; // From the dashboard URL
const res = await fetch(
`https://app.documenso.com/api/v1/templates/${templateId}/create-document`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DOCUMENSO_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Service Agreement — Acme Corp",
recipients: [
{
email: "ceo@acme.com",
name: "Alice CEO",
role: "SIGNER",
},
],
// Optionally prefill fields by their IDs
prefillFields: [
{ id: "field_abc123", value: "2026-03-22" },
{ id: "field_def456", value: "Acme Corporation" },
],
}),
}
);
const document = await res.json();
console.log(`Created document ${document.documentId} from template ${templateId}`);
Step 3: Template Workflow Patterns
// Pattern: Batch docum
Optimize Documenso usage costs and manage subscription efficiency.
Documenso Cost Tuning
Output
- A measured cost decision with document/signing quality, delivery, compliance, and retention guardrails.
- An aggregate usage receipt and reversible change record owned by the appropriate service/data lead.
Examples
Compare aggregate document volume, workflow duration, and error data in development/staging, change one approved capacity or lifecycle setting, and observe the stated window. Revert on signing/delivery/security regression; do not reduce audit, retention, authorization, or document-protection controls to lower cost.
Overview
Optimize Documenso costs through plan selection, template reuse, self-hosting, and usage monitoring. Documenso's pricing is uniquely developer-friendly: paid plans include unlimited API usage and signing volume.
Prerequisites
- Documenso account with billing access
- Understanding of your document volume patterns
Documenso Pricing Model
| Plan | Price | Documents | API / Signing | Teams | Key Feature |
|---|---|---|---|---|---|
| Free | $0/mo | Limited | Fair use | No | Personal use |
| Individual | $30/mo (early adopter) | Unlimited | Unlimited | No | Full API access |
| Team | $30/mo+ | Unlimited | Unlimited | Yes, unlimited | Team management, webhooks |
| Enterprise | Custom ($30K+/yr self-hosted) | Unlimited | Unlimited | Yes | SSO, audit logs, compliance |
| Self-Hosted (AGPL) | Free | Unlimited | No limits | Community | Full control, no SLA |
Key insight: Documenso does not charge per API call or per document on paid plans. Cost optimization is about choosing the right plan tier, not reducing API usage.
Instructions
Step 1: Right-Size Your Plan
Decision tree:
1. Personal use, < 5 docs/month? → Free tier
2. Individual developer, unlimited docs? → Individual ($30/mo)
3. Multiple team members collaborating? → Team plan
4. Need SSO, audit logs, or compliance? → Enterprise
5. Want full control, have DevOps capacity? → Self-host (AGPL, free)
Step 2: Template Reuse to Save Time (Not Money)
Templates don't save money (paid plans are unlimited), but they save developer time and reduce errors:
// WITHOUT templates: rebuild every time (slow, error-prone)
async function createContractManual(client: Documenso, signer: Signer) {
const doc = await client.documents.createV0({ title: `Contract — ${signer.name}` });
// Upload PDF, add recipient, add 6 fields... every time
// 7+ API calls per document
}
// WITH Handle document data, signatures, and PII in Documenso integrations.
Documenso Data Handling
Output
- A document-data flow with defined classification, access/retention/deletion controls, audit ownership, and safe recovery path.
- Evidence that document content, signer identity, and signature artifacts are excluded from unsafe logs and test fixtures.
Examples
Use a synthetic document and test signer in development to verify encryption/access/retention configuration. Record only a correlation ID and policy result; never place signed documents, signer PII, signature material, or document URLs into repositories, screenshots, or diagnostic logs.
Overview
Best practices for handling documents, signatures, and PII in Documenso integrations. Covers downloading signed PDFs, data retention, GDPR compliance, and secure storage. Note: Documenso cloud stores documents in PostgreSQL by default; self-hosted gives you full control.
Prerequisites
- Understanding of data protection regulations (GDPR, CCPA)
- Secure storage infrastructure (S3, GCS, or local encrypted storage)
- Completed
documenso-install-authsetup
Document Lifecycle
DRAFT ──send()──→ PENDING ──all sign──→ COMPLETED
│
├──reject()──→ REJECTED
└──cancel()──→ CANCELLED
Data handling implications:
- DRAFT: mutable, can delete freely
- PENDING: immutable document, but status changes
- COMPLETED: signed PDF available for download, archive
- REJECTED/CANCELLED: cleanup candidate
Instructions
Step 1: Download Signed Documents
import { Documenso } from "@documenso/sdk-typescript";
import { writeFile } from "node:fs/promises";
const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
async function downloadSignedPdf(documentId: number, outputPath: string) {
// Verify document is completed
const doc = await client.documents.getV0(documentId);
if (doc.status !== "COMPLETED") {
throw new Error(`Document ${documentId} is ${doc.status}, not COMPLETED`);
}
// Download via v1 REST API (SDK may not expose download directly)
const res = await fetch(
`https://app.documenso.com/api/v1/documents/${documentId}/download`,
{ headers: { Authorization: `Bearer ${process.env.DOCUMENSO_API_KEY}` } }
);
if (!res.ok) throw new Error(`Download failed: ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
await writeFile(outputPath, buffer);
console.log(`Saved signed PDF: ${outputPath} (${buffer.length} bytes)`);
}
Step 2: PII Handling
// Identify PII in Documenso data
interface RecipientPII {
email: string; // PII — must be protected
name: string; // PII — must be protected
role: string; // Not PII
signingStatus: string; // Not PII
}
// SanitComprehensive debugging toolkit for Documenso integrations.
Documenso Debug Bundle
Output
- A minimal redacted diagnostic bundle with correlation IDs, lifecycle state, environment, version, and status evidence.
- A safe escalation/recovery record that preserves document/signature confidentiality and audit integrity.
Examples
For a signing failure, collect opaque document/correlation IDs, template version, environment, state transition, callback result, and timestamp. Review the bundle for document content, signer PII, signing links, tokens, and audit payloads before sharing; reproduce only with synthetic documents through the approved incident/support route.
Current State
!node --version 2>/dev/null || echo 'N/A' !python3 --version 2>/dev/null || echo 'N/A' !uname -a
Overview
Comprehensive debugging tools for Documenso integration issues. Includes diagnostic scripts, curl debug commands, environment verification, and support ticket templates.
Prerequisites
- Documenso SDK installed
- Access to logs and configuration
curlandjqavailable
Instructions
Step 1: Quick Connectivity Test
#!/bin/bash
set -euo pipefail
echo "=== Documenso Connectivity Test ==="
# 1. Check API key is set
if [ -z "${DOCUMENSO_API_KEY:-}" ]; then
echo "FAIL: DOCUMENSO_API_KEY not set"
exit 1
fi
echo "OK: API key set (${#DOCUMENSO_API_KEY} chars)"
# 2. Test authentication
BASE="${DOCUMENSO_BASE_URL:-https://app.documenso.com/api/v1}"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $DOCUMENSO_API_KEY" \
"$BASE/documents?page=1&perPage=1")
if [ "$STATUS" = "200" ]; then
echo "OK: API authentication successful"
elif [ "$STATUS" = "401" ]; then
echo "FAIL: Invalid API key (401)"
exit 1
elif [ "$STATUS" = "403" ]; then
echo "FAIL: Insufficient permissions (403) — try a team API key"
exit 1
else
echo "WARN: Unexpected status $STATUS"
fi
# 3. Check latency
LATENCY=$(curl -s -o /dev/null -w "%{time_total}" \
-H "Authorization: Bearer $DOCUMENSO_API_KEY" \
"$BASE/documents?page=1&perPage=1")
echo "Latency: ${LATENCY}s"
# 4. List recent documents
echo "=== Recent Documents ==="
curl -s -H "Authorization: Bearer $DOCUMENSO_API_KEY" \
"$BASE/documents?page=1&perPage=5" | jq '.documents[] | {id, title, status, createdAt}'
Step 2: TypeScript Diagnostic Script
// scripts/documenso-diagnose.ts
import { Documenso } from "@documenso/sdk-typescript";
async function diagnose() {
const results: ArrDeploy Documenso integrations across different platforms and environments.
Documenso Deploy Integration
Output
- A versioned, staged document/signing deployment with owner approval, validation evidence, and rollback reference.
- A protected promotion path that prevents unreviewed configurations from affecting production documents or signers.
Examples
Deploy a synthetic document workflow to staging with scoped credentials, verify authorization, signing lifecycle, webhook verification, and redacted alerts, then use an approved production canary. Stop and roll back if audience, access, or lifecycle behavior differs; do not place document data or signing links in deployment logs.
Overview
Deploy Documenso-integrated applications and self-hosted Documenso instances to Docker, Kubernetes, serverless, and cloud platforms. Covers both app deployment (your code that uses the Documenso API) and self-hosted Documenso deployment.
Prerequisites
- Application ready for deployment
- Cloud platform account (AWS, GCP, Azure)
- Docker installed locally
- Completed
documenso-multi-env-setup
Instructions
Step 1: Dockerize Your Documenso Integration
# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app
RUN addgroup -S app && adduser -S app -G app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json .
USER app
EXPOSE 3000
CMD ["node", "dist/server.js"]
# Note: DOCUMENSO_API_KEY injected at runtime, never baked into image
Step 2: Self-Hosted Documenso (Docker Compose)
# docker-compose.prod.yml
services:
documenso:
image: documenso/documenso:latest
ports:
- "3000:3000"
environment:
- NEXTAUTH_URL=https://sign.yourcompany.com
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET} # openssl rand -hex 32
- NEXT_PRIVATE_ENCRYPTION_KEY=${ENCRYPTION_KEY}
- NEXT_PRIVATE_ENCRYPTION_SECONDARY_KEY=${ENCRYPTION_SECONDARY_KEY}
- NEXT_PUBLIC_WEBAPP_URL=https://sign.yourcompany.com
- NEXT_PRIVATE_DATABASE_URL=postgresql://documenso:${DB_PASS}@db:5432/documenso
- NEXT_PRIVATE_DIRECT_DATABASE_URL=postgresql://documenso:${DB_PASS}@db:5432/documenso
# SMTP
- NEXT_PRIVATE_SMTP_TRANSPORT=smtp-auth
- NEXT_PRIVATE_SMTP_HOST=${SMTP_HOST}
- NEXT_PRIVATE_SMTP_PORT=587
- NEXT_PRIVATE_SMTP_USERNAME=${SMTP_USER}
- NEXT_PRIVATE_SMTP_PASSWORD=${SMTP_PASS}
- NEXT_PRIVATE_SMTP_FROM_ADDRESS=signing@yourcompany.com
- NEXT_PRIVATE_SMTP_FROM_NAME=YourCompany Signing
# Signing certificate
- NEXT_PRIVATE_SIGNING_PASSPHRASE=${CERT_PASSPHRASE}
volumes:
- ./certs/signing-cert.p12:/opt/documenso/cert.p12:ro
dependConfigure Documenso enterprise role-based access control and team management.
Documenso Enterprise RBAC
Output
- A least-privilege role/project configuration with named owners, access-review evidence, and a tested revocation path.
- Verified separation between development/staging/production document and signer permissions.
Examples
Grant a development service account only the document action and project it needs, validate it with a synthetic document, and confirm it cannot view or sign production documents. Record the owner and review date; revoke overly broad access and correct group mapping before proceeding.
Overview
Configure team-based access control and enterprise features in Documenso. The Team plan enables multi-user collaboration with shared documents. Enterprise adds SSO (OIDC), audit logging, and organization-level management.
Prerequisites
- Documenso Team or Enterprise plan
- Understanding of RBAC concepts
- For SSO: OIDC-compatible identity provider (Okta, Azure AD, Google Workspace, Auth0)
Documenso Team Model
Organization
├── Team A
│ ├── Owner (full control)
│ ├── Admin (manage members, settings)
│ └── Member (create, view, sign team documents)
├── Team B
│ └── ...
└── Personal Accounts (separate from teams)
Key concepts:
- Teams are separate from personal accounts -- team documents are owned by the team
- Team API keys access all team documents; personal keys only access personal documents
- Each team member can have Owner, Admin, or Member role
- Unlimited teams and users on Team/Enterprise plans (early adopter pricing)
Instructions
Step 1: Team API Key Scoping
import { Documenso } from "@documenso/sdk-typescript";
// Personal key: only YOUR documents
const personalClient = new Documenso({
apiKey: process.env.DOCUMENSO_PERSONAL_KEY!,
});
// Team key: all documents in the team
const teamClient = new Documenso({
apiKey: process.env.DOCUMENSO_TEAM_KEY!,
});
// Common mistake: using personal key for team operations
// Results in 403 Forbidden on team resources
Step 2: Application-Level RBAC
Documenso handles team membership internally. For finer-grained control in your app, implement an authorization layer:
// src/auth/documenso-rbac.ts
type Role = "viewer" | "editor" | "admin" | "owner";
interface TeamMember {
userId: string;
teamId: string;
role: Role;
}
const PERMISSIONS: Record<Role, string[]> = {
viewer: ["documents:read"],
editor: ["documents:read", "documents:create", "documents:send"],
admin: ["documents:read", "documents:create", "documents:send", "documents:delete", "members:manage"],
owner: ["Create a minimal working Documenso example.
Documenso Hello World
Output
- A verified synthetic development document/signing workflow with a redacted lifecycle receipt.
- A cleanup/disable action that leaves no real signer or production-document tutorial artifact.
Examples
Create a development document using placeholder content and a synthetic signer, verify the intended role and lifecycle transition, then archive/delete it under the test policy. Record only environment and opaque correlation/state; never use a real agreement, signer, signing URL, or production workspace for a hello-world exercise.
Overview
Minimal working example that creates a document, adds a recipient with a signature field, and sends it for signing — all in one script. Uses the Documenso TypeScript SDK (v2 API) with a Python equivalent.
Prerequisites
- Completed
documenso-install-authsetup - Valid API key in
DOCUMENSO_API_KEYenvironment variable - A PDF file to upload (or generate a test one below)
Instructions
Step 1: Generate a Test PDF (Optional)
If you don't have a PDF handy:
npm install pdf-lib
// generate-test-pdf.ts
import { PDFDocument, StandardFonts } from "pdf-lib";
import { writeFileSync } from "fs";
async function createTestPdf() {
const pdf = PDFDocument.create();
const page = (await pdf).addPage([612, 792]); // US Letter
const font = await (await pdf).embedFont(StandardFonts.Helvetica);
page.drawText("Please sign below:", { x: 50, y: 700, size: 16, font });
const bytes = await (await pdf).save();
writeFileSync("test-contract.pdf", bytes);
console.log("Created test-contract.pdf");
}
createTestPdf();
Step 2: Complete Signing Workflow (TypeScript)
// documenso-hello.ts
import { Documenso } from "@documenso/sdk-typescript";
import { readFileSync } from "fs";
async function main() {
const client = new Documenso({
apiKey: process.env.DOCUMENSO_API_KEY!,
});
// 1. Create a document
const doc = await client.documents.createV0({
title: "Hello World Contract",
});
console.log(`Document created: ID ${doc.documentId}`);
// 2. Upload the PDF
const pdfBuffer = readFileSync("test-contract.pdf");
await client.documents.setFileV0(doc.documentId, {
file: new Blob([pdfBuffer], { type: "application/pdf" }),
});
// 3. Add a recipient (signer)
const recipient = await client.documentsRecipients.createV0(doc.documentId, {
email: "signer@example.com",
name: "Jane Doe",
role: "SIGNER",
});
console.log(`Recipient added: ${recipient.recipientId}`);
// 4. Add a signature field at specific coordinates
await client.documentsFieldManage incident response for Documenso integration issues.
Documenso Incident Runbook
Instructions
- Declare the incident scope, commander, affected documents/signers/environment, and safe communication channel.
- Stabilize with the approved pause, access-revocation, or rollback action before deep diagnosis.
- Collect only redacted correlation/state/audit evidence; preserve document/signature integrity and chain of custody.
- Verify recovery, notify owners, and create follow-up work for root cause and prevention.
Output
- A time-stamped incident record with scope, owner, mitigation, redacted evidence, and verified recovery or escalation.
Examples
For unauthorized document access, restrict affected credentials or sharing immediately, capture opaque document/correlation IDs and redacted audit state, and verify access is restored only to the intended role. Escalate according to policy; do not share documents, signing links, or signer PII in incident chat.
Overview
Step-by-step procedures for responding to Documenso integration incidents. Covers cloud outages, self-hosted issues, and integration failures.
Prerequisites
- Access to monitoring dashboards
- Documenso dashboard access
- Application log access
- On-call escalation contacts defined
Severity Levels
| Level | Description | Examples | Response Time |
|---|---|---|---|
| P1 | Complete signing outage | All API calls failing, no documents can be sent | < 15 min |
| P2 | Degraded functionality | Slow responses, intermittent errors, webhooks delayed | < 1 hour |
| P3 | Minor issue, workaround available | Single document stuck, UI glitch | < 4 hours |
| P4 | Non-urgent | Feature request, documentation gap | Next business day |
Quick Diagnostic Commands
#!/bin/bash
set -euo pipefail
echo "=== Documenso Incident Diagnostic ==="
# 1. Check Documenso cloud status
echo "--- Cloud Status ---"
curl -s https://status.documenso.com/api/v2/status.json 2>/dev/null | jq '.status' || echo "Status page unreachable"
# 2. Check our API connectivity
echo "--- API Connectivity ---"
BASE="${DOCUMENSO_BASE_URL:-https://app.documenso.com/api/v1}"
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $DOCUMENSO_API_KEY" \
"$BASE/documents?page=1&perPage=1" 2>/dev/null || echo "000")
echo "API Status: $HTTP_CODE"
# 3. Check latency (5 samples)
echo "--- Latency Check ---"
for i in $(seq 1 5); do
LATENCY=$(curl -s -o /dev/null -w "%{time_total}" \
-H "Authorization: Bearer $DOCInstall and configure Documenso SDK/API authentication.
Documenso Install & Auth
Output
- A scoped Documenso credential/reference for the intended environment, with a verified low-impact authorization check.
- A secret-ownership and revocation path that keeps tokens and signing material out of repositories and logs.
Examples
Inject a development credential from the approved secret manager, create or read a synthetic document through a least-privilege role, and record only environment/result. If a key or signing URL is exposed, revoke it first and reissue after investigation; do not reuse it while attempting cleanup.
Overview
Set up the Documenso SDK and configure API authentication for document signing. Covers the TypeScript SDK (@documenso/sdk-typescript), the Python SDK (documenso-sdk-python), and raw REST API usage. Documenso exposes two API versions: v1 (legacy, documents only) and v2 (envelopes, multi-document, recommended for new work).
Prerequisites
- Node.js 18+ or Python 3.10+
- Package manager (npm, pnpm, yarn, pip, or uv)
- Documenso account — cloud at
app.documenso.comor self-hosted instance - API key generated from the Documenso dashboard
Instructions
Step 1: Install the SDK
TypeScript / Node.js:
npm install @documenso/sdk-typescript
# or
pnpm add @documenso/sdk-typescript
Python:
pip install documenso-sdk-python
# or
uv pip install documenso-sdk-python
Step 2: Generate an API Key
- Log in to your Documenso dashboard (
https://app.documenso.comor your self-hosted URL). - Click your avatar (top-right) and select User settings (or Team settings for team-scoped keys).
- Navigate to the API tokens tab.
- Click Create API Key, give it a descriptive name (e.g.
ci-pipeline-prod). - Copy the key immediately — it is shown only once.
Team API keys inherit the team's document and template access. Personal keys only access your own documents.
Step 3: Store the Key Securely
# .env (never commit this file)
DOCUMENSO_API_KEY=api_xxxxxxxxxxxxxxxxxxxxxxxxxx
Add .env to .gitignore:
echo ".env" >> .gitignore
Step 4: Initialize the Client
TypeScript — v2 API (recommended):
import { Documenso } from "@documenso/sdk-typescript";
const documenso = new Documenso({
apiKey: process.env.DOCUMENSO_API_KEY!,
// For self-hosted, override the server URL:
// serverURL: "https://sign.yourSet up local development environment and testing workflow for Documenso.
Documenso Local Dev Loop
Output
- A small test-backed local change using synthetic documents/signers and a normal source-control rollback path.
- A redacted development verification receipt without document content, signing links, credentials, or signer PII.
Examples
Use a development workspace with a synthetic template and signer, make one integration/config change, run its focused tests and a bounded lifecycle check, then inspect redacted status. Commit only reviewed changes; never use production documents, signing URLs, or credentials in local development.
Overview
Configure a fast local development environment for Documenso integrations. Covers project structure, environment configs, self-hosted Documenso via Docker, test utilities, and cleanup scripts.
Prerequisites
- Completed
documenso-install-authsetup - Node.js 18+ with TypeScript
- Docker (for self-hosted local Documenso)
Instructions
Step 1: Project Structure
my-signing-app/
├── src/
│ └── documenso/
│ ├── client.ts # Configured SDK client
│ ├── documents.ts # Document operations
│ ├── recipients.ts # Recipient management
│ └── webhooks.ts # Webhook handlers
├── scripts/
│ ├── verify-connection.ts # Quick health check
│ ├── create-test-doc.ts # Generate test documents
│ └── cleanup-test-docs.ts # Remove test data
├── tests/
│ └── integration/
│ ├── document.test.ts
│ └── template.test.ts
├── .env.development
├── .env.test
└── .env.production
Step 2: Environment Configuration
.env.development:
DOCUMENSO_API_KEY=api_dev_xxxxxxxxxxxx
DOCUMENSO_BASE_URL=https://stg-app.documenso.com/api/v2
DOCUMENSO_WEBHOOK_SECRET=whsec_dev_xxxxxxxxxxxx
LOG_LEVEL=debug
.env.test:
DOCUMENSO_API_KEY=api_test_xxxxxxxxxxxx
DOCUMENSO_BASE_URL=https://stg-app.documenso.com/api/v2
DOCUMENSO_WEBHOOK_SECRET=whsec_test_xxxxxxxxxxxx
LOG_LEVEL=warn
Step 3: Client Wrapper with Dev Helpers
// src/documenso/client.ts
import { Documenso } from "@documenso/sdk-typescript";
let _client: Documenso | null = null;
export function getClient(): Documenso {
if (!_client) {
_client = new Documenso({
apiKey: process.env.DOCUMENSO_API_KEY!,
...(process.env.DOCUMENSO_BASE_URL && {
serverURL: process.env.DOCUMENSO_BASE_URL,
}),
});
}
return _client;
}
// Dev helper: list recent documents for debugging
export async function listRecentDocs(limit = 5) {
const client = getClient();
const { documents } = await client.documents.findV0({
page: 1,
perPage: limit,
orderByColumn: "createdAt",
orderByDirection: "desc&Execute comprehensive Documenso migration strategies for platform switches.
Documenso Migration Deep Dive
Output
- A staged migration record with document/template/signing compatibility evidence, owner, observation window, and rollback path.
- Preserved prior documents/configuration until the migration acceptance and retention requirements are complete.
Examples
Migrate a synthetic document/template set in development, verify roles, state transitions, callbacks, audit evidence, and retention, then promote through staging before a production canary. Stop and roll back on authorization, signing, or audit regression; never bulk-migrate sensitive documents as a test.
Current State
!npm list 2>/dev/null | head -10
Overview
Comprehensive guide for migrating to Documenso from other e-signature platforms (DocuSign, HelloSign, PandaDoc, Adobe Sign). Uses the Strangler Fig pattern for zero-downtime migration with feature flags and rollback support.
Prerequisites
- Current signing platform documented (APIs, templates, webhooks)
- Documenso account configured (see
documenso-install-auth) - Feature flag infrastructure (LaunchDarkly, environment variables, etc.)
- Parallel run capability (both platforms active during migration)
Migration Strategy: Strangler Fig Pattern
Phase 1: Parallel Systems (Week 1-2)
┌──────────┐ ┌─────────────┐
│ Your App │────▶│ Old Platform │ (100% traffic)
│ │ └─────────────┘
│ │────▶│ Documenso │ (shadow: log only, don't send)
└──────────┘ └─────────────┘
Phase 2: Gradual Cutover (Week 3-4)
┌──────────┐ ┌─────────────┐
│ Your App │────▶│ Old Platform │ (50% traffic via feature flag)
│ │ └─────────────┘
│ │────▶│ Documenso │ (50% traffic)
└──────────┘ └─────────────┘
Phase 3: Full Migration (Week 5+)
┌──────────┐ ┌─────────────┐
│ Your App │────▶│ Documenso │ (100% traffic)
└──────────┘ └─────────────┘
Old platform decommissioned
Instructions
Step 1: Pre-Migration Assessment
// scripts/assess-current-system.ts
// Inventory your current signing platform usage
interface MigrationAssessment {
platform: string;
activeTemplates: number;
documentsPerMonth: number;
webhookEndpoints: string[];
recipientRoles: string[];
fieldTypes: string[];
integrations: string[]; // CRM, database, etc.
}
async function assessCurrentSystem(): Promise<MigrationAssessment> {
// Example for DocuSign
return {
platform: "DocuSign",
activeTemplates: 15,
documentsPerMonth: 200,
webhookEndpoints: [
"https://api.yourapp.com/webhooks/docusign",
],
recipientRoles: ["Signer", "CC", "In Person Signer"],
fieldTypes: ["Signature", "Date", "Text", "CheConfigure Documenso across multiple environments (dev, staging, production).
Documenso Multi-Environment Setup
Output
- Isolated development, staging, and production workspaces with separate scoped identities, templates, signer controls, and audit boundaries.
- A promotion/rollback receipt based on synthetic validation rather than production document or signer experiments.
Examples
Validate a versioned template and callback in development using synthetic recipients, promote to staging with separate credentials, and record its lifecycle/authorization/alert results. Release production through an approved canary only; if any gate differs, restore the prior configuration and do not copy production keys or signing artifacts into lower environments.
Overview
Configure Documenso across development, staging, and production with environment isolation, secret management, and promotion workflows. Documenso cloud offers a staging environment at stg-app.documenso.com; self-hosted users run separate instances.
Prerequisites
- Documenso accounts or instances for each environment
- Secret management solution (Vault, AWS Secrets Manager, or
.envfiles) - Completed
documenso-install-authsetup
Environment Architecture
┌─────────────────────────────────────────────────────────────┐
│ Development │
│ API: stg-app.documenso.com (or localhost:3000 self-hosted) │
│ Key: DOCUMENSO_API_KEY=api_dev_xxx │
│ Webhooks: ngrok tunnel │
├─────────────────────────────────────────────────────────────┤
│ Staging │
│ API: stg-app.documenso.com │
│ Key: DOCUMENSO_API_KEY=api_stg_xxx │
│ Webhooks: staging.yourapp.com/webhooks/documenso │
├─────────────────────────────────────────────────────────────┤
│ Production │
│ API: app.documenso.com (or sign.yourcompany.com) │
│ Key: DOCUMENSO_API_KEY=api_prod_xxx │
│ Webhooks: api.yourapp.com/webhooks/documenso │
└─────────────────────────────────────────────────────────────┘
Instructions
Step 1: Environment Configuration Files
# .env.development
DOCUMENSO_API_KEY=api_dev_xxxxxxxxxxxx
DOCUMENSO_BASE_URL=https://stg-app.documenso.com/api/v2
DOCUMENSO_WEBHOOK_SECRET=whsec_dev_xxxxxxxxxxxx
LOG_LEVEL=debug
NODE_ENV=development
# .env.staging
DOCUMENSO_API_KEY=api_stg_xxxxxxxxxxxx
DOCUMENSO_BASE_URL=https://stg-app.documenso.com/api/v2
DOCUMENSO_WEBHOOK_SECRET=whsec_stg_xxxxxxxxxxxx
LOG_LEVEL=info
NODE_ENV=staging
# .env.production
DOCUMENSO_API_KEY=api_prod_xxxxxxxxxxxx
DOCUMENSO_BASE_URL=https://app.documenso.com/api/v2
DOCUMENSO_WEBHOOK_SECRET=whsec_prod_xxImplement monitoring, logging, and tracing for Documenso integrations.
Documenso Observability
Output
- Redacted, bounded metrics/traces for document lifecycle, signing state, errors, latency, and rate headroom.
- An owned alert/runbook path that protects signer identity, document content, and credentials.
Examples
Emit aggregate counts by environment, document state, and status class while excluding document bodies, signer email, signing URLs, IP addresses, tokens, and audit payloads. Trigger a development signing-state alert with a synthetic document, verify the on-call route, then retain only the redacted receipt.
Overview
Implement monitoring, structured logging, and health checks for Documenso integrations. Since Documenso does not expose rate limit headers or usage metrics via API, observability is built around your API call patterns, latency, error rates, and webhook delivery.
Prerequisites
- Working Documenso integration
- Monitoring stack (Prometheus/Grafana, Datadog, or CloudWatch)
- Logging infrastructure
Instructions
Step 1: Instrumented Client Wrapper
// src/observability/documenso-metrics.ts
import { Documenso } from "@documenso/sdk-typescript";
interface Metrics {
requestCount: number;
errorCount: number;
totalLatencyMs: number;
errorsByStatus: Record<number, number>;
}
const metrics: Metrics = {
requestCount: 0,
errorCount: 0,
totalLatencyMs: 0,
errorsByStatus: {},
};
export function createInstrumentedClient(): Documenso {
const client = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
return new Proxy(client, {
get(target, prop) {
const value = (target as any)[prop];
if (typeof value === "object" && value !== null) {
return new Proxy(value, {
get(innerTarget, method) {
const fn = (innerTarget as any)[method];
if (typeof fn !== "function") return fn;
return async (...args: any[]) => {
const start = Date.now();
metrics.requestCount++;
try {
const result = await fn.apply(innerTarget, args);
metrics.totalLatencyMs += Date.now() - start;
return result;
} catch (err: any) {
metrics.errorCount++;
const status = err.statusCode ?? 0;
metrics.errorsByStatus[status] = (metrics.errorsByStatus[status] || 0) + 1;
metrics.totalLatencyMs += Date.now() - start;
throw err;
}
};
},
});
}
return value;
},
});
}
// Expose metrics for Prometheus scraping
export function getMetrics() {
return {
...metrics,
avgLatencyMs: metrics.requestCount > 0
? Math.round(metrics.totalLatencyMs / metrics.requestCount)
: 0,
errorRate: metrics.requestCOptimize Documenso integration performance with caching, batching, and efficient patterns.
Documenso Performance Tuning
Output
- A measured performance change with document/signing lifecycle, authorization, audit, and reliability guardrails.
- A reversible change record with aggregate metrics, owner, threshold, and rollback decision.
Examples
Measure synthetic-document workflow latency, throughput, error rate, and callback completion in staging, change one approved capacity/cache/concurrency setting, and compare against baseline. Revert if signing state, authorization, audit, or error behavior regresses; do not use real documents or weaken controls to improve a benchmark.
Overview
Optimize Documenso integrations for speed and efficiency. Key strategies: reduce API round-trips with templates, cache document metadata, batch operations with concurrency control, and use async processing for bulk signing workflows.
Prerequisites
- Working Documenso integration
- Redis or in-memory cache (recommended)
- Completed
documenso-sdk-patternssetup
Instructions
Step 1: Reduce API Calls with Templates
The biggest performance win: templates reduce a multi-step document creation (create + upload + add recipients + add fields + send = 5+ calls) to just 2 calls (create from template + send).
// WITHOUT templates: 5+ API calls per document
async function createDocumentManual(signer: { email: string; name: string }) {
const doc = await client.documents.createV0({ title: "Contract" }); // 1
await client.documents.setFileV0(doc.documentId, { file: pdfBlob }); // 2
const recip = await client.documentsRecipients.createV0(doc.documentId, { // 3
email: signer.email, name: signer.name, role: "SIGNER",
});
await client.documentsFields.createV0(doc.documentId, { // 4
recipientId: recip.recipientId, type: "SIGNATURE",
pageNumber: 1, pageX: 10, pageY: 80, pageWidth: 30, pageHeight: 5,
});
await client.documents.sendV0(doc.documentId); // 5
}
// WITH templates: 2 API calls per document
async function createDocumentFromTemplate(templateId: number, signer: { email: string; name: string }) {
const res = await fetch( // 1
`${BASE}/templates/${templateId}/create-document`,
{
method: "POST",
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
title: `Contract — ${signer.name}`,
recipients: [{ email: signer.email, name: signer.name, role: "SIGNER" }],
}),
}
);
const doc = await res.json();
await fetch(`${BASE}/documents/${doc.documentId}/send`, { // 2
method: "POST",
headers: { Authorization: Execute Documenso production deployment checklist and rollback procedures.
Documenso Production Checklist
Instructions
- Complete evidence gates for workspace/identity, template/version review, signer authorization, data/retention, callbacks, audit, monitoring, and rollback.
- Validate the exact production role/audience and signing lifecycle with approved safe checks.
- Stop production enablement when any document, identity, security, or owner gate is unverified.
- Record the named go/no-go decision and post-release observation result.
Output
- A production-readiness receipt with owners, evidence links, approved exceptions, and tested rollback path.
Examples
Validate a new template in staging with synthetic signers, verify the production access roles and callback endpoint under review, then release to an approved canary. If authorization, state, or audit behavior differs, halt the release and restore the prior approved template.
Overview
Complete checklist for deploying Documenso integrations to production, covering security, reliability, monitoring, and compliance readiness.
Prerequisites
- Staging environment tested and verified
- Production API keys available
- Deployment pipeline configured (see
documenso-ci-integration) - Monitoring ready (see
documenso-observability)
Production Checklist
1. Authentication & Secrets
- [ ] Production API key generated (not staging key)
- [ ] API key stored in secret manager (Vault, AWS Secrets Manager, not
.env) - [ ] Webhook secret configured and verified
- [ ] Key rotation procedure documented
- [ ] Old/unused keys revoked
- [ ] Self-hosted: secrets generated with
openssl rand -hex 32 - [ ] Self-hosted: signing certificate from trusted CA mounted
2. Error Handling
- [ ] All API calls wrapped in try/catch with typed errors
- [ ] Exponential backoff for 429/5xx responses
- [ ] Circuit breaker for Documenso outages
- [ ] User-friendly error messages (no raw API errors exposed)
- [ ] Error tracking integration (Sentry, Datadog, etc.)
3. Performance
- [ ] Singleton client pattern (not creating new client per request)
- [ ] Templates used for repetitive document creation
- [ ] Bulk operations use concurrency control (p-queue)
- [ ] Background processing for non-critical operations (Bull/BullMQ)
- [ ] Document metadata cached (completed documents immutable)
4. Monitoring & Alerting
- [ ] Health check endpoint:
GET /health/documenso - [ ] API error rate alerting (> 5% for 5 minutes)
- [ ] Latency monitoring (p95 > 5s)
- [ ] Webhook delivery success rate tracking
- [ ] Structured logging with sanitized PII
5.
Implement Documenso rate limiting, backoff, and request throttling patterns.
Documenso Rate Limits
Output
- A rate-aware document/signing integration with bounded concurrency, idempotency, backoff, monitoring, and replay ownership.
- A safe throttle/recovery receipt that avoids duplicate invitations, duplicate signatures, or accidental document changes.
Examples
Exercise a development API with synthetic documents at controlled concurrency, retain stable idempotency keys, and record aggregate 429/latency/completion results. Back off with jitter on throttling; do not retry document creation or signature actions without verifying their current state.
Overview
Documenso uses a fair-use rate limiting model. There are no published per-minute request quotas -- instead, limits are based on your plan's document allowance and general API fair use. The paid plans (Individual and Team) include unlimited signing and API volume. The free plan has a document limit. If you hit a 429, implement exponential backoff and request queuing.
Prerequisites
- Documenso SDK installed
- Understanding of async/await patterns
- Completed
documenso-install-authsetup
Documenso Fair Use Model
| Plan | Documents | API Volume | Signing Volume |
|---|---|---|---|
| Free | Limited (per plan) | Fair use | Fair use |
| Individual ($30/mo) | Unlimited | Unlimited | Unlimited |
| Team | Unlimited | Unlimited | Unlimited |
| Enterprise | Unlimited | Unlimited | Unlimited |
| Self-Hosted | Unlimited | No limits | No limits |
Documenso explicitly does not price API usage -- they want developers to build on the platform without API cost concerns. The practical limit is abusive traffic patterns (thousands of requests per second).
Instructions
Step 1: Exponential Backoff with Jitter
// src/documenso/retry.ts
interface RetryConfig {
maxRetries: number;
baseDelayMs: number;
maxDelayMs: number;
}
const DEFAULTS: RetryConfig = { maxRetries: 5, baseDelayMs: 1000, maxDelayMs: 60000 };
export async function withRetry<T>(
fn: () => Promise<T>,
config: Partial<RetryConfig> = {}
): Promise<T> {
const { maxRetries, baseDelayMs, maxDelayMs } = { ...DEFAULTS, ...config };
let lastError: Error | undefined;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err: any) {
lastError = err;
const status = err.statusCode ?? err.status;
// Don't retry client errors (except 429)
if (status && status >= 400 && status < 500 && status !== 429) {
throw err;
}
if (attempImplement Documenso reference architecture with best-practice project layout.
Documenso Reference Architecture
Instructions
- Map document producers, templates, recipients, signing actions, audit records, webhooks, and retention boundaries to named owners.
- Enforce least-privilege identity and separate development/staging/production workspaces and credentials.
- Define idempotent lifecycle transitions, signed callbacks, redacted observability, and a rollback/incident path before production exposure.
- Review architecture changes through normal security, data, and change-control processes.
Output
- A documented document/signing architecture with trust boundaries, ownership, and reversible integration points.
Examples
Route a synthetic development document through a scoped service identity, role-limited signer, validated webhook, and redacted audit metric. Promote the same versioned workflow through staging before a production canary; preserve a disabled/rollback path and do not include document URLs or signer identity in diagrams or logs.
Overview
Production-ready architecture for Documenso document signing integrations. Covers project layout, layered service architecture, webhook processing, and data flow.
Prerequisites
- Understanding of layered architecture principles
- Documenso SDK knowledge (see
documenso-sdk-patterns) - TypeScript project with Node.js 18+
Recommended Project Structure
my-signing-app/
├── src/
│ ├── documenso/
│ │ ├── client.ts # Singleton SDK client
│ │ ├── errors.ts # Custom error classes
│ │ ├── retry.ts # Retry/backoff logic
│ │ └── types.ts # Shared types
│ ├── services/
│ │ ├── document-service.ts # Document CRUD operations
│ │ ├── template-service.ts # Template-based workflows
│ │ └── signing-service.ts # Orchestrates signing flows
│ ├── webhooks/
│ │ ├── handler.ts # Express webhook router
│ │ ├── verify.ts # Secret verification
│ │ └── processors/
│ │ ├── document-completed.ts
│ │ ├── document-signed.ts
│ │ └── document-rejected.ts
│ ├── api/
│ │ ├── health.ts # Health check endpoint
│ │ └── routes.ts # API routes
│ └── config/
│ └── index.ts # Environment configuration
├── scripts/
│ ├── verify-connection.ts # Quick health check
│ ├── create-test-doc.ts # Test document generator
│ └── cleanup-test-docs.ts # Test data cleanup
├── tests/
│ ├── unit/
│ │ └── document-service.test.ts
│ ├── integration/
│ │ └── document-lifecycle.test.ts
│ └── mocks/
│ └── documenso.ts # Mock client factory
├── .env.development
├── .env.production
├── docker-compose.yml # Self-hosted Documenso (dev)
└── package.json
Layer Archi
Apply production-ready Documenso SDK patterns for TypeScript and Python.
Documenso SDK Patterns
Output
- A scoped SDK boundary with document authorization, idempotency, redacted telemetry, and safe error handling.
- A test-backed client design that never logs signing URLs, document content, signer PII, or credentials.
Examples
Instantiate the SDK with a development secret reference, create a synthetic test document with a stable idempotency key, and assert the mocked request shape in unit tests. For one development integration check, record only correlation ID and lifecycle state; never log document or signer payloads.
Overview
Production-ready patterns for the Documenso TypeScript SDK (@documenso/sdk-typescript) and Python SDK. Covers singleton clients, typed wrappers, error handling, retry logic, and testing patterns.
Prerequisites
- Completed
documenso-install-authsetup - Familiarity with async/await and TypeScript generics
- Understanding of error handling best practices
Instructions
Pattern 1: Singleton Client with Configuration
// src/documenso/client.ts
import { Documenso } from "@documenso/sdk-typescript";
interface DocumensoConfig {
apiKey: string;
baseUrl?: string;
timeout?: number;
}
let instance: Documenso | null = null;
export function getDocumensoClient(config?: DocumensoConfig): Documenso {
if (!instance) {
const apiKey = config?.apiKey ?? process.env.DOCUMENSO_API_KEY;
if (!apiKey) throw new Error("DOCUMENSO_API_KEY is required");
instance = new Documenso({
apiKey,
...(config?.baseUrl && { serverURL: config.baseUrl }),
});
}
return instance;
}
// Reset for testing
export function resetClient(): void {
instance = null;
}
Pattern 2: Typed Document Service
// src/documenso/documents.ts
import { getDocumensoClient } from "./client";
export interface CreateDocumentInput {
title: string;
pdfPath: string;
signers: Array<{
email: string;
name: string;
fields: Array<{
type: "SIGNATURE" | "INITIALS" | "NAME" | "EMAIL" | "DATE" | "TEXT";
pageNumber: number;
pageX: number;
pageY: number;
pageWidth?: number;
pageHeight?: number;
}>;
}>;
}
export interface DocumentResult {
documentId: number;
recipientIds: number[];
status: "DRAFT" | "PENDING" | "COMPLETED";
}
export async function createAndSendDocument(
input: CreateDocumentInput
): Promise<DocumentResult> {
const client = getDocumensoClient();
const { readFileSync } = await import("fs");
// Create document
const doc = await client.documents.createV0({ title: input.title });
// Upload PDF
const pdfBuffer = readFileSync(input.pdfPath)Implement security best practices for Documenso document signing integrations.
Documenso Security Basics
Output
- A least-privilege Documenso configuration with scoped secrets, signer/document access controls, and an incident/revocation path.
- A tested boundary for document authorization, webhook validation, and safe audit logging.
Examples
Create a development document with a synthetic signer, validate that only its intended role can view or act on it, and verify any webhook signature before processing. If a token, signing URL, or document is exposed, revoke/contain access and follow the incident procedure before attempting cleanup.
Overview
Essential security practices for Documenso integrations: API key management, webhook verification, document access control, and self-hosted signing certificate configuration.
Prerequisites
- Documenso account with API access
- Understanding of environment variables and secret management
- Completed
documenso-install-authsetup
Instructions
Step 1: API Key Security
// NEVER hardcode keys
const BAD = new Documenso({ apiKey: "api_abc123..." }); // Exposed in source
// ALWAYS use environment variables
const GOOD = new Documenso({ apiKey: process.env.DOCUMENSO_API_KEY! });
Key management rules:
- Store in
.env(never committed) or a secrets manager (Vault, AWS Secrets Manager) - Use team-scoped keys for team resources, personal keys for personal documents
- Rotate keys on employee offboarding -- revoke in dashboard immediately
- CI/CD: use masked/encrypted secrets (GitHub Secrets, GitLab CI variables)
# .gitignore — always include
.env
.env.*
!.env.example
Step 2: Key Rotation with Zero Downtime
// Support dual keys during rotation
function getApiKey(): string {
// Try primary first, fall back to secondary during rotation
return process.env.DOCUMENSO_API_KEY_PRIMARY
?? process.env.DOCUMENSO_API_KEY_SECONDARY
?? (() => { throw new Error("No Documenso API key configured"); })();
}
// Rotation procedure:
// 1. Generate new key in Documenso dashboard
// 2. Set as DOCUMENSO_API_KEY_SECONDARY, deploy
// 3. Verify secondary key works
// 4. Move secondary to PRIMARY, deploy
// 5. Revoke old key in dashboard
Step 3: Webhook Secret Verification
import { timingSafeEqual } from "crypto";
function verifyWebhookSecret(req: Request): boolean {
const received = req.headers["x-documenso-secret"] as string;
const expected = process.env.DOCUMENSO_WEBHOOK_SECRET!;
if (!received || !expected) return false;
// Use constant-time comparison to prevent timing attacks
return timingSafeEqual(
Buffer.from(received, "utf8"),
Manage Documenso API version upgrades and SDK migrations.
Documenso Upgrade & Migration
Output
- A versioned upgrade record with compatibility, access/audit checks, staged evidence, and a verified rollback revision.
- A paused/reversible release decision when any signing, authorization, or retention requirement regresses.
Examples
Upgrade in a development workspace using synthetic documents and signers, test the previous and target versions for lifecycle, callback, access, and audit behavior, then stage a canary. Retain the prior release/configuration and roll back immediately if a control fails; do not validate upgrades by changing live signed documents.
Current State
!npm list @documenso/sdk-typescript 2>/dev/null || echo 'SDK not installed' !npm list documenso-sdk-python 2>/dev/null || pip show documenso-sdk-python 2>/dev/null | head -3 || echo 'Python SDK not installed'
Overview
Guide for upgrading between Documenso API versions and SDK updates. Documenso has two API versions: v1 (legacy, document-centric) and v2 (recommended, envelope-based with multi-document support). The TypeScript and Python SDKs use the v2 API by default.
Prerequisites
- Current Documenso integration working
- Test environment available
- Feature flag system (recommended for gradual rollout)
API Version Comparison
| Feature | v1 (legacy) | v2 (recommended) |
|---|---|---|
| Base path | /api/v1/ |
/api/v2/ |
| Document model | Documents | Envelopes (can contain multiple documents) |
| SDK support | REST only | TypeScript + Python SDK |
| Template API | /templates/{id}/create-document |
Via envelope create |
| Authentication | Authorization: Bearer |
Authorization: Bearer (same) |
| Status | Maintained, not deprecated | Actively developed |
Instructions
Step 1: Upgrade SDK to Latest
# Check current version
npm list @documenso/sdk-typescript
# Upgrade
npm install @documenso/sdk-typescript@latest
# Check for breaking changes
npm info @documenso/sdk-typescript changelog
# Python
pip install --upgrade documenso-sdk-python
Step 2: v1 REST to v2 SDK Migration
// BEFORE: v1 REST API
const BASE = "https://app.documenso.com/api/v1";
const headers = { Authorization: `Bearer ${process.env.DOCUMENSO_API_KEY}` };
// Create document
const res = await fetch(`${BASE}/documents`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSOImplement Documenso webhook configuration and event handling.
Documenso Webhooks & Events
Output
- A verified signed, idempotent webhook/event path with redacted observability and recovery ownership.
- A receipt that records correlation ID, environment, event type, lifecycle result, and safe retry decision.
Examples
Validate the callback signature before parsing the event, deduplicate with an opaque event ID, acknowledge within the documented timeout, and log only state/result metadata. Test in development using a synthetic document; retry transient errors with bounded backoff and quarantine terminal failures without replaying signing actions blindly.
Overview
Configure and handle Documenso webhooks for real-time document lifecycle notifications. Webhooks require a Teams plan or higher. The webhook secret is sent via the X-Documenso-Secret header (not HMAC-signed -- it is a shared secret comparison).
Prerequisites
- Documenso team account (webhooks require teams)
- HTTPS endpoint for webhook reception
- Completed
documenso-install-authsetup
Supported Events
| Event | Trigger | Use Case |
|---|---|---|
document.created |
New document created | Audit logging |
document.sent |
Document sent for signing | Start SLA timers |
document.opened |
Recipient opens the document | Track engagement |
document.signed |
One recipient completes signing | Progress tracking |
document.completed |
All recipients have signed | Trigger downstream workflows |
document.rejected |
Recipient rejects | Alert sender, escalate |
document.cancelled |
Sender cancels document | Cleanup, notify recipients |
Instructions
Step 1: Create Webhook via Dashboard
- Log into Documenso, navigate to Team Settings > Webhooks.
- Click Create Webhook.
- Enter your HTTPS endpoint URL.
- Select the events you want to receive.
- (Optional) Enter a webhook secret -- this value will be sent as-is in the
X-Documenso-Secretheader on every request. - Save.
Step 2: Webhook Handler (Express)
// src/webhooks/documenso.ts
import express from "express";
const router = express.Router();
const WEBHOOK_SECRET = process.env.DOCUMENSO_WEBHOOK_SECRET!;
// Middleware: verify the shared secret
function verifySecret(req: express.Request, res: express.Response, next: express.NextFunction) {
const secret = req.headers["x-documenso-secret&How It Works
Skills trigger automatically when you discuss Documenso topics:
- "Help me set up Documenso" triggers
documenso-install-auth - "Debug this Documenso error" triggers
documenso-common-errors - "Configure Documenso webhooks" triggers
documenso-webhooks-events - "Deploy my Documenso integration" triggers
documenso-deploy-integration - "Migrate from DocuSign" triggers
documenso-migration-deep-dive
Ready to use documenso-pack?
Related Plugins
supabase-pack
Complete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack.
/plugin install supabase-pack@claude-code-plugins-plus
vercel-pack
Complete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack.
/plugin install vercel-pack@claude-code-plugins-plus
clay-pack
Complete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack.
/plugin install clay-pack@claude-code-plugins-plus
cursor-pack
Complete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack.
/plugin install cursor-pack@claude-code-plugins-plus
exa-pack
Complete Exa integration skill pack with 30 skills covering neural search, semantic retrieval, web search API, and AI-powered discovery. Flagship+ tier vendor pack.
/plugin install exa-pack@claude-code-plugins-plus
firecrawl-pack
Complete Firecrawl integration skill pack with 30 skills covering web scraping, crawling, markdown conversion, and LLM-ready data extraction. Flagship+ tier vendor pack.
/plugin install firecrawl-pack@claude-code-plugins-plus