A reusable, production-ready DocuSign service wrapper for Node.js applications with support for JWT authentication, template-based contracts, and fully customizable HTML documents with SOLID architecture.
- β JWT Authentication - Secure authentication using JWT tokens
- β Template-based Contracts - Send contracts from DocuSign templates
- β Custom HTML Rendering - 4 flexible ways to customize document HTML
- β SOLID Architecture - Extensible renderer system following best practices
- β Embedded Signing - Generate signing URLs for embedded signing experience
- β Document Download - Download signed documents as PDFs
- β TypeScript Support - Full TypeScript definitions included
- β Framework Agnostic - Works with Express, NestJS, or any Node.js framework
- π HTML Template Support - Use custom templates with
{{placeholder}}syntax - π Custom Renderer Functions - Full programmatic control over HTML generation
- π Reusable Renderer Classes - Create and share custom renderers across projects
npm install docusign-azimBefore using this package, you need to:
- Create a DocuSign Developer account at developers.docusign.com
- Create an Integration Key (Client ID)
- Generate an RSA keypair for JWT authentication
- Get your User ID and Account ID
- Grant admin consent for your integration
import { DocuSignService } from "docusign-azim";
import * as fs from "fs";
// Initialize the service
const docusign = new DocuSignService({
integrationKey: "your-integration-key",
userId: "your-user-id",
accountId: "your-account-id",
baseUrl: "https://demo.docusign.net/restapi", // Use https://na1.docusign.net/restapi for production
privateKey: fs.readFileSync("./keys/private.key", "utf8"), // Or pass file path
redirectUrl: "https://yourapp.com/docusign/callback",
});
// Send a contract from a template
const result = await docusign.sendContractFromTemplate({
templateId: "template-id",
signerEmail: "signer@example.com",
signerName: "John Doe",
customFields: {
company_name: "Acme Corp",
contract_date: "2024-01-15",
},
});
console.log("Signing URL:", result.signingUrl);
console.log("Envelope ID:", result.envelopeId);interface DocuSignConfig {
integrationKey: string; // Your DocuSign Integration Key
userId: string; // Your DocuSign User ID (GUID format)
accountId: string; // Your DocuSign Account ID
baseUrl: string; // API base URL
privateKey: string; // Private key (PEM string or file path)
redirectUrl: string; // Redirect URL after signing
appUrl?: string; // Optional: App URL for iframe embedding
oauthBaseUrl?: string; // Optional: OAuth base URL (default: account-d.docusign.com)
}DOCUSIGN_INTEGRATION_KEY=your-integration-key
DOCUSIGN_USER_ID=your-user-id
DOCUSIGN_ACCOUNT_ID=your-account-id
DOCUSIGN_BASE_URL=https://demo.docusign.net/restapi
DOCUSIGN_PRIVATE_KEY_PATH=./keys/private.key
DOCUSIGN_REDIRECT_URL=https://yourapp.com/callbackconst result = await docusign.sendContractFromTemplate({
templateId: "abc123-template-id",
signerEmail: "client@example.com",
signerName: "Jane Smith",
subject: "Service Agreement - Please Sign",
emailBody: "Please review and sign this service agreement.",
customFields: {
client_name: "Jane Smith",
project_name: "Website Development",
start_date: "2024-02-01",
total_amount: "$5,000",
},
products: [
{
no: 1,
item: "Web Development",
qty: 1,
price: "$5,000",
total: "$5,000",
},
],
});// Use the built-in default quotation template
const result = await docusign.sendContractWithCustomData({
signerEmail: "client@example.com",
signerName: "Jane Smith",
subject: "Quotation Q-2024-001",
customFields: {
no: "Q-2024-001",
date: "2024-01-15",
project: "Website Redesign",
subtotal: "$4,500",
tax: "$450",
total: "$4,950",
},
products: [
{
no: 1,
item: "UI/UX Design",
qty: 40,
price: "$75/hr",
total: "$3,000",
},
{
no: 2,
item: "Frontend Development",
qty: 20,
price: "$75/hr",
total: "$1,500",
},
],
});// Provide your own HTML template with {{placeholders}}
const customTemplate = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; padding: 40px; }
.header { background: #4CAF50; color: white; padding: 20px; }
</style>
</head>
<body>
<div class="header">
<h1>{{companyName}}</h1>
<p>Invoice #{{invoiceNumber}}</p>
</div>
<p>Client: {{signerName}}</p>
<p>Date: {{currentDate}}</p>
<table>
<thead><tr><th>Item</th><th>Qty</th><th>Price</th><th>Total</th></tr></thead>
<tbody>{{productsTable}}</tbody>
</table>
<h2>Total: {{total}}</h2>
<p>Sign Here</p>
</body>
</html>
`;
const result = await docusign.sendContractWithCustomData({
signerEmail: "client@example.com",
signerName: "Jane Smith",
htmlTemplate: customTemplate,
documentName: "Professional Invoice",
signatureAnchor: "Sign Here",
signaturePosition: { x: 450, y: 700 },
customFields: {
companyName: "Acme Corporation",
invoiceNumber: "INV-2024-001",
total: "$5,000.00",
},
products: [...],
});import type { HtmlRenderData } from "docusign-azim";
// Full programmatic control over HTML generation
const customRenderer = (data: HtmlRenderData): string => {
const { customFields, products, signerName, currentDate } = data;
// Calculate totals dynamically
const total = products?.reduce(
(sum, p) => sum + parseFloat(p.total.replace(/[$,]/g, "")), 0
);
return `
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 40px;
}
.document {
background: white;
padding: 60px;
border-radius: 15px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
</style>
</head>
<body>
<div class="document">
<h1>${customFields.title}</h1>
<p>For: ${signerName}</p>
<p>Date: ${currentDate}</p>
${products?.map(p => `
<div class="item">${p.item}: ${p.total}</div>
`).join('')}
<h2>Total: $${total?.toFixed(2)}</h2>
<p>Sign Here</p>
</div>
</body>
</html>
`;
};
const result = await docusign.sendContractWithCustomData({
signerEmail: "client@example.com",
signerName: "Bob Johnson",
htmlRenderer: customRenderer,
documentName: "Dynamic Proposal",
customFields: {
title: "Business Proposal",
},
products: [...],
});const signingInfo = await docusign.getSigningUrl({
envelopeId: "envelope-id",
signerEmail: "client@example.com",
signerName: "Jane Smith",
});
console.log("Signing URL:", signingInfo.signingUrl);
console.log("Expires at:", signingInfo.expiresAt);const pdfBuffer = await docusign.downloadDocument({
envelopeId: "envelope-id",
documentId: "combined", // or specific document ID
});
// Save to file
fs.writeFileSync("signed-contract.pdf", pdfBuffer);const refreshed = await docusign.refreshSigningUrl("envelope-id");
console.log("New signing URL:", refreshed.signingUrl);
console.log("Recipient info:", refreshed.recipientInfo);Send a contract from a DocuSign template.
Parameters:
templateId- DocuSign template IDsignerEmail- Signer's emailsignerName- Signer's full namecustomFields- Object with field names and valuessubject- (Optional) Email subjectemailBody- (Optional) Email bodyproducts- (Optional) Array of products for DocuSign Gen templates
Returns: Promise<SendEnvelopeResult>
Send a contract with custom HTML content. Supports 4 rendering methods:
- Default Renderer - Built-in professional quotation template
- HTML Template - Provide template string with
{{placeholders}} - Renderer Function - Full programmatic control
- Renderer Class - Reusable custom renderer extending
BaseHtmlRenderer
Parameters:
signerEmail- Signer's emailsignerName- Signer's full namecustomFields- Object with field names and valuessubject- (Optional) Email subjectemailBody- (Optional) Email bodyproducts- (Optional) Array of products for quotation tablehtmlTemplate- (Optional) Custom HTML template string with{{placeholders}}htmlRenderer- (Optional) Custom renderer function(data: HtmlRenderData) => stringdocumentName- (Optional) Document name (default: "Service Agreement")signatureAnchor- (Optional) Text to anchor signature (default: "Sign Here")signaturePosition- (Optional) Signature position{ x: number, y: number }
Returns: Promise<SendEnvelopeResult>
Example with all options:
await docusign.sendContractWithCustomData({
signerEmail: "client@example.com",
signerName: "John Doe",
subject: "Please sign this document",
emailBody: "Review and sign at your convenience",
documentName: "Business Proposal",
signatureAnchor: "Sign Here",
signaturePosition: { x: 450, y: 700 },
htmlTemplate: "...", // OR htmlRenderer: (data) => "...",
customFields: {
companyName: "Acme Corp",
invoiceNumber: "INV-001",
},
products: [...],
});Generate or regenerate a signing URL.
Parameters:
envelopeId- DocuSign envelope IDsignerEmail- Signer's emailsignerName- Signer's full namerecipientId- (Optional) Recipient IDclientUserId- (Optional) Client user ID
Returns: Promise<SigningUrlResult>
Download a signed document.
Parameters:
envelopeId- DocuSign envelope IDdocumentId- (Optional) Document ID, defaults to "combined"
Returns: Promise<Buffer>
Refresh signing URL for an envelope.
Parameters:
envelopeId- DocuSign envelope ID
Returns: Promise<RefreshSigningUrlResult>
import express from "express";
import { DocuSignService } from "docusign-azim";
const app = express();
const docusign = new DocuSignService({
// ... config
});
app.post("/send-contract", async (req, res) => {
try {
const result = await docusign.sendContractFromTemplate({
templateId: req.body.templateId,
signerEmail: req.body.email,
signerName: req.body.name,
customFields: req.body.fields,
});
res.json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get("/signing/:envelopeId", async (req, res) => {
try {
const result = await docusign.refreshSigningUrl(req.params.envelopeId);
res.redirect(result.signingUrl);
} catch (error) {
res.status(500).json({ error: error.message });
}
});import { Injectable } from "@nestjs/common";
import { DocuSignService } from "docusign-azim";
@Injectable()
export class ContractService {
private docusign: DocuSignService;
constructor() {
this.docusign = new DocuSignService({
integrationKey: process.env.DOCUSIGN_INTEGRATION_KEY!,
userId: process.env.DOCUSIGN_USER_ID!,
accountId: process.env.DOCUSIGN_ACCOUNT_ID!,
baseUrl: process.env.DOCUSIGN_BASE_URL!,
privateKey: process.env.DOCUSIGN_PRIVATE_KEY_PATH!,
redirectUrl: process.env.DOCUSIGN_REDIRECT_URL!,
});
}
async sendContract(data: any) {
return this.docusign.sendContractFromTemplate(data);
}
}The package throws descriptive errors for common issues:
try {
const result = await docusign.sendContractFromTemplate({
// ... params
});
} catch (error) {
if (error.message.includes("consent_required")) {
// Admin consent needed - redirect user to consent URL
console.log("Visit consent URL:", error.message);
} else if (error.message.includes("invalid_grant")) {
// Invalid credentials
console.error("Check your integration key, user ID, or private key");
} else {
console.error("Error:", error.message);
}
}npm install
npm run build# Login to npm
npm login
# Publish
npm publish- Go to DocuSign Admin (or production admin)
- Navigate to Integrations β Apps and Keys
- Click Add App and Integration Key
- Note your Integration Key
- In your integration settings, click Generate RSA
- Download the private key and save it securely
- Copy the public key (DocuSign stores this automatically)
- In DocuSign Admin, go to Users
- Click on your user
- Copy the API Username (GUID format)
- In DocuSign Admin, go to Settings β API and Keys
- Copy your API Account ID
After setting up your integration, run your application once. It will provide a consent URL. Visit this URL and grant consent for the impersonation scope.
The package provides 4 flexible ways to customize document HTML, following SOLID principles:
Just pass your data - uses professional built-in template:
await docusign.sendContractWithCustomData({
signerEmail: "client@example.com",
signerName: "John Doe",
customFields: { no: "Q-001", total: "$5,000" },
products: [...]
});Provide custom HTML with {{placeholder}} syntax:
const template = `
<!DOCTYPE html>
<html>
<body>
<h1>{{companyName}}</h1>
<p>Invoice: {{invoiceNumber}}</p>
<p>Client: {{signerName}}</p>
<p>Date: {{currentDate}}</p>
<table>{{productsTable}}</table>
<h2>Total: {{total}}</h2>
<p>Sign Here</p>
</body>
</html>
`;
await docusign.sendContractWithCustomData({
...params,
htmlTemplate: template,
});Available placeholders:
{{fieldName}}- Any custom field{{signerName}}- Signer's name{{currentDate}}- Current date formatted{{productsTable}}- Auto-generated table rows{{#hasProducts}}...{{/hasProducts}}- Conditional if products exist{{#noProducts}}...{{/noProducts}}- Conditional if no products
Full programmatic control:
import type { HtmlRenderData } from "docusign-azim";
const myRenderer = (data: HtmlRenderData): string => {
const { customFields, products, signerName, currentDate } = data;
// Your custom logic
const total = products?.reduce((sum, p) =>
sum + parseFloat(p.total.replace(/[$,]/g, "")), 0
);
return `
<html>
<body>
<h1>${customFields.title}</h1>
<p>${signerName} - ${currentDate}</p>
<h2>$${total?.toFixed(2)}</h2>
<p>Sign Here</p>
</body>
</html>
`;
};
await docusign.sendContractWithCustomData({
...params,
htmlRenderer: myRenderer,
});Create reusable renderer classes:
import { BaseHtmlRenderer, type HtmlRenderData } from "docusign-azim";
class MyCompanyRenderer extends BaseHtmlRenderer {
constructor(private branding: { color: string; logo: string }) {
super();
}
render(data: HtmlRenderData): string {
// Use helper methods
const rows = this.generateProductRows(data.products);
const safeName = this.escapeHtml(data.signerName);
return `
<html>
<body style="color: ${this.branding.color}">
<img src="${this.branding.logo}" />
<h1>Invoice for ${safeName}</h1>
<table>${rows}</table>
<p>Sign Here</p>
</body>
</html>
`;
}
}
// Reuse across your app
const renderer = new MyCompanyRenderer({
color: "#1a73e8",
logo: "https://mycompany.com/logo.png"
});
await docusign.sendContractWithCustomData({
...params,
htmlRenderer: (data) => renderer.render(data),
});BaseHtmlRenderer helper methods:
replacePlaceholders(template, fields, signerName)- Replace{{placeholders}}generateProductRows(products)- Generate HTML table rowsescapeHtml(text)- Prevent XSS attacks
For detailed examples, best practices, and advanced usage, see:
- Custom HTML Guide - Comprehensive rendering documentation
- Advanced Examples - Real-world examples
MIT
Contributions are welcome! Please feel free to submit a Pull Request.
For issues or questions:
- GitHub Issues: Create an issue
- DocuSign Support: developers.docusign.com
- Documentation: See CUSTOM_HTML_GUIDE.md for detailed rendering docs
- β¨ Added 4 flexible HTML rendering methods
- β¨ Template string support with
{{placeholder}}syntax - β¨ Custom renderer function support for full control
- β¨ Reusable renderer classes extending
BaseHtmlRenderer - β¨ SOLID architecture with Strategy Pattern
- β¨ Conditional template sections (
{{#hasProducts}}) - β¨ Custom signature positioning
- β¨ XSS protection with HTML escaping
- π Comprehensive documentation and examples
- π§ Helper methods for common rendering tasks
- Initial release
- JWT authentication support
- Template-based contracts
- Custom HTML contracts
- Embedded signing
- Document download
- TypeScript support