Â
A type-safe SDK for seamless integration with Documenso v2 API, providing first-class TypeScript support.
This SDK offers a strongly-typed interface to interact with Documenso's API, enabling you to:
- Handle document signing workflows with full type safety
- Leverage autocomplete in your IDE
- Catch potential errors at compile time
The full Documenso API can be viewed here (todo), which includes TypeScript examples.
Documenso v2 API and SDKs are currently in beta. There may be to breaking changes.
To keep updated, please follow the discussions and issues here:
- Discussion -> Todo
- Breaking change alerts -> Todo
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @documenso/sdk-typescript
pnpm add @documenso/sdk-typescript
bun add @documenso/sdk-typescript
yarn add @documenso/sdk-typescript zod
# Note that Yarn does not install peer dependencies automatically. You will need
# to install zod as shown above.
For supported JavaScript runtimes, please consult RUNTIMES.md.
To use the SDK, you will need a Documenso API key which can be created here.
const documenso = new Documenso({
apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});
Currently creating a document involves two steps:
- Create the document
- Upload the PDF
This is a temporary measure, in the near future prior to the full release we will merge these two tasks into one request.
Here is a full example of the document creation process which you can copy and run.
Note that the function is temporarily called createV0
, which will be replaced by create
once we resolve the 2 step workaround.
import { Documenso } from "@documenso/sdk-typescript";
import fs from "fs";
const documenso = new Documenso({
apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});
async function uploadFileToPresignedUrl(filePath: string, uploadUrl: string) {
const fileBuffer = await fs.promises.readFile(filePath);
// Make PUT request to pre-signed URL
const response = await fetch(uploadUrl, {
method: "PUT",
body: fileBuffer,
headers: {
"Content-Type": "application/octet-stream",
},
});
if (!response.ok) {
throw new Error(`Upload failed with status: ${response.status}`);
}
}
const main = async () => {
const createDocumentResponse = await documenso.documents.createV0({
title: "Document title",
recipients: [
{
email: "[email protected]",
name: "Example Doe",
role: "SIGNER",
fields: [
{
type: "SIGNATURE",
pageNumber: 1,
pageX: 10,
pageY: 10,
width: 10,
height: 10,
},
{
type: "INITIALS",
pageNumber: 1,
pageX: 20,
pageY: 20,
width: 10,
height: 10,
},
],
},
{
email: "[email protected]",
name: "Admin Doe",
role: "APPROVER",
fields: [
{
type: "SIGNATURE",
pageNumber: 1,
pageX: 10,
pageY: 50,
width: 10,
height: 10,
},
],
},
],
meta: {
timezone: "Australia/Melbourne",
dateFormat: "MM/dd/yyyy hh:mm a",
language: "de",
subject: "Email subject",
message: "Email message",
emailSettings: {
recipientRemoved: false,
},
},
});
const { document, uploadUrl } = createDocumentResponse;
// Upload the PDF you want attached to the document.
// Replace demo.pdf with your file to upload relative to this file.
await uploadFileToPresignedUrl("./demo.pdf", uploadUrl);
return document;
};
main()
Available methods
- find - Find documents
- get - Get document
- createV0 - Create document
- update - Update document
- delete - Delete document
- moveToTeam - Move document
- distribute - Distribute document
- redistribute - Redistribute document
- duplicate - Duplicate document
- get - Get document field
- create - Create document field
- createMany - Create document fields
- update - Update document field
- updateMany - Update document fields
- delete - Delete document field
- get - Get document recipient
- create - Create document recipient
- createMany - Create document recipients
- update - Update document recipient
- updateMany - Update document recipients
- delete - Delete document recipient
- find - Find templates
- get - Get template
- update - Update template
- duplicate - Duplicate template
- delete - Delete template
- use - Use template
- moveToTeam - Move template
- create - Create template field
- get - Get template field
- createMany - Create template fields
- update - Update template field
- updateMany - Update template fields
- delete - Delete template field
- get - Get template recipient
- create - Create template recipient
- createMany - Create template recipients
- update - Update template recipient
- updateMany - Update template recipients
- delete - Delete template recipient
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Documenso } from "@documenso/sdk-typescript";
const documenso = new Documenso({
apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});
async function run() {
const result = await documenso.documents.find({
orderByDirection: "desc",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
// Handle the result
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Documenso } from "@documenso/sdk-typescript";
const documenso = new Documenso({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});
async function run() {
const result = await documenso.documents.find({
orderByDirection: "desc",
});
// Handle the result
console.log(result);
}
run();
Some methods specify known errors which can be thrown. All the known errors are enumerated in the models/errors/errors.ts
module. The known errors for a method are documented under the Errors tables in SDK docs. For example, the find
method may throw the following errors:
Error Type | Status Code | Content Type |
---|---|---|
errors.DocumentFindDocumentsResponseBody | 400 | application/json |
errors.DocumentFindDocumentsDocumentsResponseBody | 404 | application/json |
errors.DocumentFindDocumentsDocumentsResponseResponseBody | 500 | application/json |
errors.APIError | 4XX, 5XX | */* |
If the method throws an error and it is not captured by the known errors, it will default to throwing a APIError
.
import { Documenso } from "@documenso/sdk-typescript";
import {
DocumentFindDocumentsDocumentsResponseBody,
DocumentFindDocumentsDocumentsResponseResponseBody,
DocumentFindDocumentsResponseBody,
SDKValidationError,
} from "@documenso/sdk-typescript/models/errors";
const documenso = new Documenso({
apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});
async function run() {
let result;
try {
result = await documenso.documents.find({
orderByDirection: "desc",
});
// Handle the result
console.log(result);
} catch (err) {
switch (true) {
// The server response does not match the expected SDK schema
case (err instanceof SDKValidationError): {
// Pretty-print will provide a human-readable multi-line error message
console.error(err.pretty());
// Raw value may also be inspected
console.error(err.rawValue);
return;
}
case (err instanceof DocumentFindDocumentsResponseBody): {
// Handle err.data$: DocumentFindDocumentsResponseBodyData
console.error(err);
return;
}
case (err instanceof DocumentFindDocumentsDocumentsResponseBody): {
// Handle err.data$: DocumentFindDocumentsDocumentsResponseBodyData
console.error(err);
return;
}
case (err
instanceof DocumentFindDocumentsDocumentsResponseResponseBody): {
// Handle err.data$: DocumentFindDocumentsDocumentsResponseResponseBodyData
console.error(err);
return;
}
default: {
// Other errors such as network errors, see HTTPClientErrors for more details
throw err;
}
}
}
}
run();
Validation errors can also occur when either method arguments or data returned from the server do not match the expected format. The SDKValidationError
that is thrown as a result will capture the raw value that failed validation in an attribute called rawValue
. Additionally, a pretty()
method is available on this error that can be used to log a nicely formatted multi-line string since validation errors can list many issues and the plain error string may be difficult read when debugging.
In some rare cases, the SDK can fail to get a response from the server or even make the request due to unexpected circumstances such as network conditions. These types of errors are captured in the models/errors/httpclienterrors.ts
module:
HTTP Client Error | Description |
---|---|
RequestAbortedError | HTTP request was aborted by the client |
RequestTimeoutError | HTTP request timed out due to an AbortSignal signal |
ConnectionError | HTTP client was unable to make a request to a server |
InvalidRequestError | Any input used to create a request is invalid |
UnexpectedClientError | Unrecognised or unexpected error |
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console
's interface as an SDK option.
Warning
Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Documenso } from "@documenso/sdk-typescript";
const sdk = new Documenso({ debugLogger: console });
You can also enable a default debug logger by setting an environment variable DOCUMENSO_DEBUG
to true.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.