Skip to content
documenso-sdk-patterns logo

Documenso SDK Patterns

documenso-sdk-patterns

Apply production-ready Documenso SDK patterns for TypeScript and Python.

SKILL.md

Full skill instructions

Documenso SDK Patterns

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-auth setup
  • 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);
  await client.documents.setFileV0(doc.documentId, {
    file: new Blob([pdfBuffer], { type: "application/​pdf" }),
  });

  // Add recipients and fields
  const recipientIds: number[] = [];
  for (const signer of input.signers) {
    const recipient = await client.documentsRecipients.createV0(doc.documentId, {
      email: signer.email,
      name: signer.name,
      role: "SIGNER",
    });
    recipientIds.push(recipient.recipientId);

    for (const field of signer.fields) {
      await client.documentsFields.createV0(doc.documentId, {
        recipientId: recipient.recipientId,
        type: field.type,
        pageNumber: field.pageNumber,
        pageX: field.pageX,
        pageY: field.pageY,
        pageWidth: field.pageWidth ?? 20,
        pageHeight: field.pageHeight ?? 5,
      });
    }
  }

  // Send
  await client.documents.sendV0(doc.documentId);

  return { documentId: doc.documentId, recipientIds, status: "PENDING" };
}

Pattern 3: Error Handling Wrapper

// src/​documenso/​errors.ts

export class DocumensoError extends Error {
  constructor(
    message: string,
    public statusCode?: number,
    public retryable: boolean = false
  ) {
    super(message);
    this.name = "DocumensoError";
  }
}

export async function withErrorHandling<T>(
  operation: string,
  fn: () => Promise<T>
): Promise<T> {
  try {
    return await fn();
  } catch (err: any) {
    const status = err.statusCode ?? err.status;
    switch (status) {
      case 401:
        throw new DocumensoError(`${operation}: Invalid API key`, 401, false);
      case 403:
        throw new DocumensoError(
          `${operation}: Insufficient permissions — use team API key`,
          403,
          false
        );
      case 404:
        throw new DocumensoError(`${operation}: Resource not found`, 404, false);
      case 429:
        throw new DocumensoError(`${operation}: Rate limited`, 429, true);
      case 500:
      case 502:
      case 503:
        throw new DocumensoError(
          `${operation}: Documenso server error`,
          status,
          true
        );
      default:
        throw new DocumensoError(
          `${operation}: ${err.message ?? "Unknown error"}`,
          status,
          false
        );
    }
  }
}

Pattern 4: Retry with Exponential Backoff

// src/​documenso/​retry.ts
import { DocumensoError } from "./​errors";

interface RetryConfig {
  maxRetries: number;
  baseDelayMs: number;
  maxDelayMs: number;
}

const DEFAULT_RETRY: RetryConfig = {
  maxRetries: 3,
  baseDelayMs: 1000,
  maxDelayMs: 30000,
};

export async function withRetry<T>(
  fn: () => Promise<T>,
  config: Partial<RetryConfig> = {}
): Promise<T> {
  const { maxRetries, baseDelayMs, maxDelayMs } = { ...DEFAULT_RETRY, ...config };
  let lastError: Error | undefined;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      lastError = err as Error;
      if (err instanceof DocumensoError && !err.retryable) throw err;
      if (attempt === maxRetries) break;

      const delay = Math.min(baseDelayMs * 2 ** attempt, maxDelayMs);
      const jitter = delay * (0.5 + Math.random() * 0.5);
      await new Promise((r) => setTimeout(r, jitter));
    }
  }
  throw lastError;
}

Pattern 5: Python Service Pattern

# src/​documenso/​service.py
from documenso_sdk_python import Documenso
from dataclasses import dataclass
from typing import Optional
import os

@dataclass
class SignerInput:
    email: str
    name: str
    field_type: str = "SIGNATURE"
    page: int = 1
    x: float = 50.0
    y: float = 80.0

class DocumensoService:
    def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
        self.client = Documenso(
            api_key=api_key or os.environ["DOCUMENSO_API_KEY"],
            **({"server_url": base_url} if base_url else {}),
        )

    def create_and_send(
        self, title: str, pdf_path: str, signers: list[SignerInput]
    ) -> dict:
        doc = self.client.documents.create_v0(title=title)

        with open(pdf_path, "rb") as f:
            self.client.documents.set_file_v0(doc.document_id, file=f.read())

        recipient_ids = []
        for signer in signers:
            recip = self.client.documents_recipients.create_v0(
                doc.document_id, email=signer.email, name=signer.name, role="SIGNER"
            )
            recipient_ids.append(recip.recipient_id)

            self.client.documents_fields.create_v0(
                doc.document_id,
                recipient_id=recip.recipient_id,
                type=signer.field_type,
                page_number=signer.page,
                page_x=signer.x,
                page_y=signer.y,
            )

        self.client.documents.send_v0(doc.document_id)
        return {"document_id": doc.document_id, "recipient_ids": recipient_ids}

Pattern 6: Testing with Mocks

// tests/​mocks/​documenso.ts
import { vi } from "vitest";

export function createMockClient() {
  return {
    documents: {
      createV0: vi.fn().mockResolvedValue({ documentId: 1 }),
      setFileV0: vi.fn().mockResolvedValue(undefined),
      findV0: vi.fn().mockResolvedValue({ documents: [] }),
      sendV0: vi.fn().mockResolvedValue(undefined),
      deleteV0: vi.fn().mockResolvedValue(undefined),
    },
    documentsRecipients: {
      createV0: vi.fn().mockResolvedValue({ recipientId: 100 }),
    },
    documentsFields: {
      createV0: vi.fn().mockResolvedValue({ fieldId: 200 }),
    },
  };
}

Error Handling

Pattern IssueCauseSolution
Client not initializedMissing env varCheck DOCUMENSO_API_KEY is set
Singleton stale after key rotationCached clientCall resetClient()
Retry loop on 401Non-retryable treated as retryableCheck retryable flag
Type mismatch on field typeWrong enum stringUse union type from SDK

Resources

Next Steps

Apply patterns in documenso-core-workflow-a for document creation workflows.

More skills from jeremylongshore

openrouter-compliance-review logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-compliance-review

Review OpenRouter integration for regulatory compliance (SOC2, GDPR,

2.8K 0
View
maintainx-data-handling logo
jeremylongshore/claude-code-plugins-plus-skills

maintainx-data-handling

Data synchronization, ETL patterns, and data management for MaintainX.

2.8K 0
View
groq-core-workflow-a logo
jeremylongshore/claude-code-plugins-plus-skills

groq-core-workflow-a

Execute Groq primary workflow: chat completions with tool use and JSON

2.8K 0
View
validating-csrf-protection logo
jeremylongshore/claude-code-plugins-plus-skills

validating-csrf-protection

Validate CSRF protection implementations for security gaps. Use when

2.8K 0
View
api-contract logo
jeremylongshore/claude-code-plugins-plus-skills

api-contract

Configure this skill should be used when the user asks about "API contract",

2.8K 0
View
ideogram-incident-runbook logo
jeremylongshore/claude-code-plugins-plus-skills

ideogram-incident-runbook

Execute Ideogram incident response with triage, mitigation, and postmortem.

2.8K 0
View
gamma-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

gamma-sdk-patterns

Reusable patterns for the Gamma REST API (no SDK exists).

2.8K 0
View
deepgram-sdk-patterns logo
jeremylongshore/claude-code-plugins-plus-skills

deepgram-sdk-patterns

Apply production-ready Deepgram SDK patterns for TypeScript and Python.

2.8K 0
View
openrouter-upgrade-migration logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-upgrade-migration

Migrate to OpenRouter from direct provider APIs or upgrade between SDK/model

2.8K 0
View
openrouter-common-errors logo
jeremylongshore/claude-code-plugins-plus-skills

openrouter-common-errors

Diagnose and fix common OpenRouter API errors. Use when encountering

2.8K 0
View
linear-cost-tuning logo
jeremylongshore/claude-code-plugins-plus-skills

linear-cost-tuning

Optimize Linear API usage, reduce unnecessary calls, and maximize

2.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View