# TypeScript (/docs/sdks/typescript)

> Render documents, wait for async renders, verify webhooks and create embedded editor sessions with the official TypeScript SDK.

`@druckling/sdk` is the official TypeScript and JavaScript client for the Druckling API. It's built on `fetch` and Web Crypto with no runtime dependencies, so the same code runs on Node.js, Bun, Deno, Cloudflare Workers and Vercel Functions. Requests, responses, webhook events and errors are typed.

## Install [#install]

Requirements:

- Node.js 20 or later, or any runtime with `fetch` and Web Crypto (`globalThis.crypto.subtle`).
- No runtime dependencies. The package ships ESM and CommonJS builds with type declarations.

The package isn't on npm yet. Build it from the Druckling source repository and install the tarball:

<Steps>
<Step>

### Build the package [#build-the-package]

```bash
git clone https://github.com/vulpery/druckling.git
cd druckling/src/integrations/sdk-typescript
npm install && npm run build && npm pack
```

`npm pack` writes `druckling-sdk-0.1.0.tgz` to that folder.

</Step>
<Step>

### Add it to your project [#add-it-to-your-project]

```bash
npm install /path/to/druckling-sdk-0.1.0.tgz
```

</Step>
<Step>

### Set your API key [#set-your-api-key]

Create a key under **Developers › API keys** and export it:

```bash
export DRUCKLING_API_KEY=dr_test_...
```

</Step>
</Steps>

Import the client as the default export or by name. CommonJS works too:

```ts
import Druckling from "@druckling/sdk";
// or: import { Druckling } from "@druckling/sdk";
// or: const { Druckling } = require("@druckling/sdk");
```

## Configuration [#configuration]

```ts
import { Druckling } from "@druckling/sdk";

const druckling = new Druckling({
  apiKey: process.env.DRUCKLING_API_KEY,
  baseUrl: "https://druckling-nine.vercel.app",
  timeoutMs: 60_000,
  maxRetries: 2,
});
```

| Option | Default | Notes |
| --- | --- | --- |
| `apiKey` | `DRUCKLING_API_KEY` | An `dr_test_…` or `dr_live_…` key, sent as `Authorization: Bearer …`. The constructor throws a `DrucklingError` when there's none. |
| `baseUrl` | `DRUCKLING_BASE_URL`, then `https://druckling-nine.vercel.app` | With or without a trailing `/v1`. |
| `timeoutMs` | `60000` | Per HTTP attempt, see [Retries and timeouts](#retries-and-timeouts). |
| `maxRetries` | `2` | Retries after the first attempt. `0` turns retries off. |
| `fetch` | `globalThis.fetch` | Your own `fetch` implementation. |
| `defaultHeaders` | none | Extra headers on every API request. |

Environment variables are read where `process.env` exists (Node.js, Bun). In other runtimes, such as Cloudflare Workers, pass `apiKey` and `baseUrl` explicitly.

### Per-request options [#per-request-options]

Every method takes request options as its last argument: `{ timeoutMs, maxRetries, signal, headers }`. They override the client's settings for that call:

```ts
const document = await druckling.documents.get("pdf_8Qw2kLm3nP0aB1cD", { timeoutMs: 5_000, maxRetries: 0 });
```

`druckling.withOptions(options)` returns a copy of the client with some options changed, for example a longer timeout for large reports:

```ts
const patient = druckling.withOptions({ timeoutMs: 180_000 });
```

`druckling.mode` is `"test"` for `dr_test_…` keys and `"live"` otherwise. `druckling.baseUrl` is the origin requests go to, without `/v1`.

### Custom fetch [#custom-fetch]

Pass `fetch` to route requests through your own implementation, for example to add metrics or tracing. It receives the same arguments as the global `fetch`, including the requests to signed download URLs:

```ts
const druckling = new Druckling({
  fetch: async (input, init) => {
    const started = Date.now();
    const response = await fetch(input, init);
    metrics.timing("druckling.request", Date.now() - started, { status: String(response.status) });
    return response;
  },
});
```

## Render a document [#render-a-document]

`documents.create` validates `data` against the template's JSON Schema and renders the document. By default it waits for the file and resolves with a `rendered` document:

```ts
import { writeFile } from "node:fs/promises";
import Druckling from "@druckling/sdk";

const druckling = new Druckling();

const invoice = {
  invoice: { number: "INV-2041", due_date: "2026-11-22" },
  customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" },
  line_items: [
    { description: "Brand identity, phase 2", qty: 1, rate: 4800, amount: 4800 },
    { description: "Design system audit", qty: 12, rate: 180, amount: 2160 },
  ],
  totals: { subtotal: 6960, tax: 556.8, amount: 7516.8 },
  payment: { url: "https://pay.example.com/INV-2041" },
};

const document = await druckling.documents.create({
  template: "invoice-standard",
  filename: "INV-2041.pdf",
  data: invoice,
});

console.log(document.id, document.status, document.pages); // pdf_… rendered 1
await writeFile("INV-2041.pdf", await druckling.documents.download(document));
```

The parameters are `template` (slug), `data`, and optionally `version` (a published version number, default `"latest"`), `filename`, `async`, `language` and `format`. The returned `Document` uses the API's field names (`size_bytes`, `content_type`, `created_at`, …), so it matches the [API reference](/docs/api-reference/documents/create) and webhook payloads one to one.

`data` must match the template's schema. `(await druckling.templates.get("invoice-standard")).sample_data` is a payload that renders. See [Variables](/docs/concepts/variables).

## Render asynchronously and wait [#render-asynchronously-and-wait]

Pass `async: true` to queue the render. `create` resolves right away with status `queued`, and the file is rendered in the background. Use `documents.wait` to poll until it's done, or [receive a webhook](#webhooks):

```ts
import { DocumentFailedError, WaitTimeoutError } from "@druckling/sdk";

const queued = await druckling.documents.create({ template: "invoice-standard", data: invoice, async: true });
console.log(queued.status); // queued

try {
  const document = await druckling.documents.wait(queued, { timeoutMs: 120_000, intervalMs: 1_000 });
  const pdf = await druckling.documents.download(document);
} catch (error) {
  if (error instanceof DocumentFailedError) {
    console.error(error.document.error?.message);
  } else if (error instanceof WaitTimeoutError) {
    console.warn(`still ${error.document.status}, check again later`);
  } else {
    throw error;
  }
}
```

`wait(document, options?)` accepts a `Document` or a document ID and polls `documents.get`:

| Option | Default | Notes |
| --- | --- | --- |
| `timeoutMs` | `120000` | Overall time to wait. |
| `intervalMs` | `1000` | Time between polls. |
| `signal` | none | An `AbortSignal` that stops waiting. |

It resolves with the document once it's `rendered`. It throws `DocumentFailedError` when the document ends `failed` or `expired` (`error.document` holds it), and `WaitTimeoutError` when the next poll would pass the timeout (`error.document` is the last state seen). Each poll is an API request and counts toward your key's rate limit.

## Download the file [#download-the-file]

`documents.download(document, options?)` resolves with the file as a `Uint8Array`: a PDF, a PNG or an XML e-invoice, depending on the document's `format`. It fetches the file from the document's signed `url`; your API key isn't sent there.

```ts
const bytes = await druckling.documents.download(document);
await writeFile(document.filename, bytes);
```

- Pass a document ID instead of a `Document` to fetch the document first and get a fresh signed URL. Do that for documents you stored earlier: a signed URL works for at most 7 days, and never after the file is deleted at `expires_at`.
- A document that is `failed` or `expired` throws `DocumentFailedError`. One that is still `queued` or `rendering` throws a `DrucklingError`; call `wait` first.
- A failed request to the signed URL throws an `APIError` with `code: "download_failed"`.

## PNG and XML output [#png-and-xml-output]

Pass `format: "png"` to render the first page as a PNG at 144 dpi instead of a PDF:

```ts
const preview = await druckling.documents.create({ template: "invoice-standard", data: invoice, format: "png" });
console.log(preview.content_type, preview.pages); // image/png 1
await writeFile("INV-2041.png", await druckling.documents.download(preview));
```

The SDK doesn't support the API's `image` options yet (`image.page` to pick another page, `image.scale` from 0.5 to 4 pixels per point, 36 to 288 dpi), and the `Document` type doesn't declare the `image` field. To use them, call the API directly and hand the result to the SDK's helpers:

```ts
import type { Document } from "@druckling/sdk";

const response = await fetch("https://druckling-nine.vercel.app/v1/documents", {
  method: "POST",
  headers: { authorization: `Bearer ${process.env.DRUCKLING_API_KEY}`, "content-type": "application/json" },
  body: JSON.stringify({ template: "invoice-standard", data: invoice, format: "png", image: { page: 1, scale: 4 } }),
});
if (!response.ok) throw new Error(`Render failed with HTTP ${response.status}: ${await response.text()}`);

const hiRes = (await response.json()) as Document;
await writeFile("INV-2041@4x.png", await druckling.documents.download(hiRes));
```

XML output is for e-invoice templates set to XRechnung or Peppol BIS: they render `format: "xml"` by default, `content_type` is `application/xml`, and `document.einvoice` describes the format and profile. Factur-X / ZUGFeRD templates render a PDF/A-3 only. A `format` the template can't produce throws a `ValidationError` with `field: "format"`. See [PNG output](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing).

## Languages [#languages]

A template can have several languages: a default one plus translations. Pass `language` to render one of them. For example, after adding German to the `invoice-standard` template:

```ts
const template = await druckling.templates.get("invoice-standard");
console.log(template.language, template.languages); // en ["en", "de"], default first

const rechnung = await druckling.documents.create({
  template: "invoice-standard",
  language: "de",
  filename: "RE-2041.pdf",
  data: invoice,
});
console.log(rechnung.language); // de
```

Without `language` the template's default is used. Texts without a translation fall back to the default language; numbers, dates, hyphenation and the PDF's language metadata follow the requested one. A regional tag such as `"de-AT"` renders `"de"`. A language the template doesn't have throws a `ValidationError` with `field: "language"`. See [Languages](/docs/guides/languages).

## List documents [#list-documents]

`documents.list(params?)` returns documents newest first. Await it for one page, or iterate it with `for await` to walk every matching document; the SDK fetches the following pages as you go:

```ts
for await (const document of druckling.documents.list({ status: "failed", template: "invoice-standard" })) {
  console.log(document.id, document.created_at, document.error?.message);
}

const page = await druckling.documents.list({ limit: 20 });
page.data;          // up to 20 documents
page.next_cursor;   // pass as `cursor` to resume later, or null
page.hasNextPage(); // boolean
await page.getNextPage(); // the next CursorPage, or null
```

Filters: `status` (`queued`, `rendering`, `rendered`, `failed`, `expired`), `template` (slug), `limit` (1 to 100, default 25) and `cursor`. A test key lists test documents, a live key live ones. See [List documents](/docs/api-reference/documents/list).

## Templates [#templates]

```ts
const { data: templates } = await druckling.templates.list();
for (const template of templates) {
  console.log(template.slug, template.status, template.latest_version, template.required_fields);
}

const template = await druckling.templates.get("invoice-standard");
template.json_schema; // the JSON Schema `data` is validated against
template.sample_data; // a payload that renders
```

- Reading templates needs a **Full access** key; a **Render only** key gets a `PermissionDeniedError`.
- `templates.list()` resolves with `{ object: "list", data }` holding every template of the workspace, drafts included. It isn't paginated. See [List templates](/docs/api-reference/templates/list) and [Retrieve a template](/docs/api-reference/templates/get).
- `json_schema`, `sample_data`, `required_fields` and `languages` come from the latest published version, or from the draft if the template was never published.
- Only published templates render. Pin a version with `documents.create({ ..., version: 3 })`.

## Errors [#errors]

Every error the SDK throws extends `DrucklingError`. Errors from the API are `APIError` subclasses:

```text
DrucklingError
├── APIError
│   ├── ValidationError
│   ├── AuthenticationError
│   ├── PermissionDeniedError
│   ├── NotFoundError
│   ├── ConflictError
│   ├── RenderError
│   ├── RateLimitError
│   │   └── QuotaExceededError
│   └── ServerError
├── APIConnectionError
│   └── APITimeoutError
├── DocumentFailedError
├── WaitTimeoutError
└── WebhookVerificationError
```

The class follows Druckling's error `code` first, then the HTTP status:

| Error | When |
| --- | --- |
| `ValidationError` | `422` `schema_validation_failed` (`data` doesn't match the schema) or `validation_failed` (for example an unknown `language`, a `format` the template can't produce, or a broken e-invoice business rule), and `400` malformed requests (`bad_request`). |
| `AuthenticationError` | `401` `unauthorized`: missing, invalid or revoked API key. |
| `PermissionDeniedError` | `403` `forbidden`: the key lacks a permission, for example a Render only key reading templates or managing webhooks. |
| `NotFoundError` | `404` `not_found`: unknown document, template, webhook endpoint or editor session, or a template without a published version. |
| `ConflictError` | `409` `conflict` or `invalid_state`: the resource's current state doesn't allow the request. |
| `RenderError` | `render_failed` (`422`) or `render_timeout` (`504`): the template couldn't be rendered, or took too long. |
| `RateLimitError` | `429` `rate_limited`, after the automatic retries. |
| `QuotaExceededError` | `429` `quota_exceeded`: the plan's document quota is used up. Never retried. |
| `ServerError` | Any other `5xx`. |
| `APIError` | Any other HTTP error (such as `413` `payload_too_large`), a failed download from a signed URL (`download_failed`), or a successful response that isn't JSON (`invalid_response`). |
| `APIConnectionError` | No HTTP response: DNS, TLS or network failure. `APITimeoutError` when the attempt timed out. |
| `DocumentFailedError` | `wait` or `download` found the document `failed` or `expired`. `error.document` holds it. |
| `WaitTimeoutError` | `wait` ran out of time. `error.document` is the last state seen. |
| `WebhookVerificationError` | A webhook's signature, timestamp or body didn't verify. |

An `APIError` carries:

| Property | Type | Notes |
| --- | --- | --- |
| `status` | `number` | HTTP status. |
| `code` | `ErrorCode` | Druckling's error code, for example `schema_validation_failed`. See [Errors](/docs/concepts/errors). |
| `message` | `string` | Human-readable description. |
| `field` | `string` or `null` | Dotted path of the offending field, for example `customer.name` or `language`. |
| `errors` | `FieldError[]` | Every offending field: `{ field, message, rule? }`. `rule` names a broken e-invoice business rule such as `BR-CO-25`. |
| `documentId` | `string` or `null` | The failed document recorded for a payload that didn't validate. |
| `retryAfter` | `number` or `null` | Seconds from the response's `Retry-After` header, when it has one. |
| `requestId` | `string` or `null` | Quote it when you contact support. |
| `headers` | `Headers` | Response headers. |
| `body` | `unknown` | Parsed JSON body, or the raw text when it isn't JSON. |

```ts
import { APIError, QuotaExceededError, RateLimitError, ValidationError } from "@druckling/sdk";

try {
  await druckling.documents.create({ template: "invoice-standard", data: { customer: {} } });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.message); // Required field invoice was missing from the request payload
    console.log(error.documentId); // pdf_… (the failed document is kept for your logs)
    for (const { field, message } of error.errors) console.log(field, "→", message);
    // invoice → missing required field invoice
    // line_items → missing required field line_items
    // totals → missing required field totals
    // customer.name → missing required field customer.name
    // customer.address → missing required field customer.address
  } else if (error instanceof QuotaExceededError) {
    notifyBilling(error.message);
  } else if (error instanceof RateLimitError) {
    requeueLater();
  } else if (error instanceof APIError) {
    console.error(error.status, error.code, error.message, error.requestId);
  } else {
    throw error;
  }
}
```

Check `QuotaExceededError` before `RateLimitError`, since it's a subclass.

## Retries and timeouts [#retries-and-timeouts]

The client retries failed requests up to `maxRetries` times (default 2):

- `429 rate_limited` is retried for every request, including renders: a rate-limited request produced no file.
- `429 quota_exceeded` is never retried; you get a `QuotaExceededError` right away.
- `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` requests only, including downloads from signed URLs.
- `POST` requests (`documents.create`, `webhookEndpoints.create`, `embedSessions.create`) aren't retried after a `5xx`, a timeout or a connection error. The API has no idempotency keys yet, so a retry could render the document twice and count twice toward your quota. Catch `ServerError` and `APIConnectionError` and decide yourself, for example by listing recent documents first.

Waits grow exponentially (0.5 s, 1 s, 2 s, … up to 8 s) with jitter. When a response carries a `Retry-After` header of up to 60 seconds, the SDK waits that long instead; a longer one is thrown to you without retrying.

`timeoutMs` (default 60 seconds) limits each attempt, including reading the response. Synchronous renders happen inside the request, so leave room for large documents, or render them with `async: true`. When you abort a request with your own `signal`, the SDK rethrows the signal's reason instead of an `APITimeoutError`, and doesn't retry.

## Webhooks [#webhooks]

Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec: `webhook-id`, `webhook-timestamp` and `webhook-signature` headers, signed with HMAC-SHA256 over the raw body.

### Verify signatures [#verify-signatures]

`verifyWebhook(payload, headers, secret, options?)` checks the signature and the timestamp, then resolves with the typed event. Pass the **raw** body, before any JSON parsing; re-serialized JSON won't match the signature.

```ts title="app/api/webhooks/druckling/route.ts"
import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk";

export async function POST(request: Request) {
  let event;
  try {
    event = await verifyWebhook(await request.text(), request.headers, process.env.DRUCKLING_WEBHOOK_SECRET!);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw error;
  }

  if (event.type === "document.rendered") {
    await saveInvoice(event.data.id, event.data.url);
  }
  return new Response(null, { status: 204 });
}
```

With Express, use `express.raw()` on the webhook route so the body stays a `Buffer`:

```ts title="server.ts"
import express from "express";
import { verifyWebhook, WebhookVerificationError } from "@druckling/sdk";

const app = express();

app.post("/webhooks/druckling", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await verifyWebhook(req.body, req.headers, process.env.DRUCKLING_WEBHOOK_SECRET!);
    if (event.type === "document.failed") await alertOps(event.data.error?.message);
    res.sendStatus(204);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return res.sendStatus(400);
    throw error;
  }
});
```

| Parameter | Type | Notes |
| --- | --- | --- |
| `payload` | `string`, `Uint8Array` (or `Buffer`), `ArrayBuffer` | The raw request body. |
| `headers` | `Headers`, or a plain object such as Node's `req.headers` | Header names are matched case-insensitively. |
| `secret` | `string` | The endpoint's `whsec_…` signing secret. |
| `options.toleranceSeconds` | `number` | Maximum age and clock skew of `webhook-timestamp`. Default `300`. |
| `options.now` | `Date` | Override the current time, for tests. |

The event is `{ id, object: "event", type, created_at, test_mode, data }`. For `document.rendered`, `document.failed` and `document.expired`, `data` is a `Document`, and checking `event.type` narrows it.

- **Duplicates**: a delivery can arrive more than once. Use `event.id` (the same as the `webhook-id` header) to ignore repeats; a resent event keeps its ID.
- **Answer fast**: respond with a `2xx` within 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer `410 Gone` unless you want Druckling to stop: it disables the endpoint.
- **Secret rotation**: after you rotate a secret in the dashboard, deliveries are signed with the new and the old secret for 24 hours. Verification passes with either, so deploy the new secret within that window.
- **Test events**: **Send test event** on **Developers › Webhooks** delivers a `webhook.ping` event; `data` is `{ object: "ping", endpoint_id, message }`.
- **Batches**: `batch.completed` events verify like any other, but the SDK's event types don't include them yet. Compare `event.type as string` against `"batch.completed"` and treat `event.data` as the batch.

`verifyWebhookSignature(payload, headers, secret, options?)` checks the signature without parsing the body. To test your handler, `await signWebhook(secret, id, timestamp, body)` returns a valid `webhook-signature` value (`timestamp` in Unix seconds or a `Date`).

### Manage webhook endpoints [#manage-webhook-endpoints]

Managing endpoints needs a **Full access** key. Endpoints belong to the key's mode: one created with a test key receives only test-mode events.

```ts
const endpoint = await druckling.webhookEndpoints.create({
  url: "https://example.com/webhooks/druckling",
  events: ["document.rendered", "document.failed"],
  description: "Invoice mailer",
});
console.log(endpoint.id, endpoint.secret); // whe_… whsec_…

const { data: endpoints } = await druckling.webhookEndpoints.list();
await druckling.webhookEndpoints.get(endpoint.id);
await druckling.webhookEndpoints.delete(endpoint.id); // { id, object: "webhook_endpoint", deleted: true }
```

The `secret` is returned only by `create`: store it now. The URL must be a public `https://` URL. See [Webhooks](/docs/guides/webhooks) for the event payloads and delivery details, and the [webhook endpoint reference](/docs/api-reference/webhooks/create) for every field.

## Embedded editor sessions [#embedded-editor-sessions]

Let your users edit a template inside your product with Druckling's white-label editor. Allow your app's origin in **Settings › Embed** first. Then, when a signed-in user opens the editor, your backend creates a short-lived session with a **Full access** key and hands its `url` to that user's browser:

```ts title="app/api/template-editor/route.ts"
import Druckling from "@druckling/sdk";

const druckling = new Druckling();

export async function POST(request: Request) {
  const user = await requireUser(request); // your own authentication

  const session = await druckling.embedSessions.create({
    template: "invoice-standard",
    permissions: { publish: true },
    user: { id: user.id, name: user.name },
    theme: { mode: "system", accent: "#0f766e" },
    expiresIn: 1800,
  });

  return Response.json({ url: session.url }, { headers: { "cache-control": "no-store" } });
}
```

| Parameter | Default | Notes |
| --- | --- | --- |
| `template` | required | Slug of the template to edit. |
| `permissions.publish` | `false` | Let the user publish new versions. By default they edit the draft and you publish. |
| `permissions.assistant` | `false` | Offer the AI assistant, on plans that include it. The returned `permissions.assistant` says whether it's on. |
| `user` | none | `{ id, name? }`: shown in request logs and on the versions the user publishes. |
| `theme` | `{ mode: "light" }` | `mode` is `light`, `dark` or `system`; `accent` is a `#rgb` or `#rrggbb` color. |
| `expiresIn` | `1800` | Seconds until the session ends, 60 to 3600. |

In the browser, mount the `url` with `mountEditor` from `@druckling/embed`, or load it in an iframe yourself. See [Embedded editor](/docs/guides/embedded-editor), and the reference for [creating](/docs/api-reference/embedded-editor/create) and [revoking](/docs/api-reference/embedded-editor/revoke) sessions.

- The `url` carries the session token in its fragment (`#token=…`). Give it only to the signed-in user's browser; never log, cache or store it. Only `create` returns it.
- `druckling.embedSessions.revoke(session.id)` ends a session right away, for example when the user signs out. It resolves with the session, now `status: "revoked"` and `url: null`. Revoking twice is fine.
- `create` throws `ConflictError` (`invalid_state`) until an origin is allowed in **Settings › Embed**, `PermissionDeniedError` for a Render only key, `ValidationError` for bad options, and `RateLimitError` beyond about 60 sessions a minute per workspace.

## Test and live keys [#test-and-live-keys]

The API key decides the mode of every request:

- `dr_test_…` keys are for development. Test renders are free and never count toward your plan's quota. Documents you list, webhook endpoints and their events stay separate from live data, and every resource carries `test_mode: true`.
- `dr_live_…` keys are for production. Live renders count toward your plan's quota.

`druckling.mode` tells you which one a client uses. See [Test mode](/docs/concepts/test-mode).

## Next steps [#next-steps]

<Cards>
  <Card title="API reference" href="/docs/api-reference">
    Every endpoint, field and error of the REST API the SDK wraps.
  </Card>
  <Card title="Webhooks" href="/docs/guides/webhooks">
    Event payloads, delivery retries and secret rotation.
  </Card>
  <Card title="Errors" href="/docs/concepts/errors">
    What each error code means and how to handle it.
  </Card>
</Cards>
