Skip to content
Menu · Node.js

SDKs

Node.js

Install @composa-labs/node, set up the client, and print documents, batches and webhooks from JavaScript or TypeScript.

The official JavaScript and TypeScript library for the Composa API. Source: github.com/Composa-Labs/composa-node.

It runs on Node.js 22 or later, Bun, Deno, Cloudflare Workers and Vercel Edge, with no runtime dependencies. It is for servers only: an API key does not belong in a browser.

Install

bash
npm install @composa-labs/node

Setup

Make an API key on the API keys page of the app (see Authentication), then:

ts
import { Composa } from '@composa-labs/node';​const composa = new Composa('cmp_live_...');

Leave the key out to read COMPOSA_API_KEY from the environment. The constructor throws when it finds no key. Nothing else throws for an API or network failure: every call resolves to { data, error, headers }. See Errors.

documents.create

Prints one document with POST /v1/run.

ts
import { writeFile } from 'node:fs/promises';​const { data, error } = await composa.documents.create({  templateId: '85416813-8d99-46e8-be2b-1d61cee5db38',  data: { full_name: 'Ada Lovelace', course: 'Engineering' },});​if (error) {  console.error(`${error.name}: ${error.message}`);  process.exit(1);}​await writeFile(data.filename ?? 'document.pdf', data.content);

data holds the template's fields by their own names. The other options are format ('pdf', 'png', 'jpg', 'webp', 'svg'), quality, scale, width, pages, language and version.

Pass output: 'url' for a link instead of the file:

ts
const { data, error } = await composa.documents.create({  templateId: '85416813-8d99-46e8-be2b-1d61cee5db38',  data: { full_name: 'Ada Lovelace' },  output: 'url',});if (error) throw new Error(error.message);​console.log(data.url, data.pages, data.bytes);

A link works for an hour (urlExpiresIn): download the file rather than storing the link.

templates.get

Reads a template's fields with GET /v1/contract.

ts
const { data: template, error } = await composa.templates.get(  '85416813-8d99-46e8-be2b-1d61cee5db38',);if (error) throw new Error(error.message);​console.log(`Version ${template.version}`);for (const field of template.fields) {  console.log(field.name, field.kind, field.ifNoValue, field.columns ?? '');}

Pass { version: 3 } as the second argument to read a version other than the active one.

batches.create

Starts a batch of up to 50,000 documents.

ts
const { data: batch, error } = await composa.batches.create({  templateId: '85416813-8d99-46e8-be2b-1d61cee5db38',  items: [    { name: 'ada', data: { full_name: 'Ada Lovelace' } },    { name: 'grace', data: { full_name: 'Grace Hopper' } },  ],});if (error) throw new Error(error.message);

A batch of any size is one call: when its items come to more than 4 MB of JSON, the SDK sends them as a file by itself (up to 64 MB). That upload counts as one more of the Team's print calls a minute. Pass data alone, in place of items, for a batch of one. Pictures go in data as https:// addresses, not as base64.

batches.waitFor

Reads the batch every 2 seconds until it ends (completed, failed, expired, canceled) or pauses, for 10 minutes at most. Change that with intervalMs, timeoutMs and signal.

ts
const { data: done, error: waitError } = await composa.batches.waitFor(batch.batchId);if (waitError) throw new Error(waitError.message);​for (const item of done.items ?? []) {  if ('outputUrl' in item) console.log(item.name, item.outputUrl);  else if ('error' in item) console.log(item.name, 'failed:', item.error);}

batches.get

Reads a batch once. Items come up to 1,000 at a time (nextOffset):

ts
const { data: page } = await composa.batches.get(batch.batchId, { offset: 1000, limit: 1000 });

batches.cancel

ts
const { data: canceled } = await composa.batches.cancel(batch.batchId);console.log(canceled?.status); // 'canceling' or 'canceled'

webhooks.verify

Checks a webhook's signature on the raw body and resolves with the typed event, or rejects with a WebhookVerificationError (answer 400). It lives on the client, so the receiver makes a Composa client, which needs an API key. Keep the signing secret in COMPOSA_WEBHOOK_SECRET, or pass secret.

ts
import { Composa, WebhookVerificationError } from '@composa-labs/node';​interface Env {  COMPOSA_API_KEY: string;  COMPOSA_WEBHOOK_SECRET: string;}​export default {  async fetch(request: Request, env: Env): Promise<Response> {    const composa = new Composa(env.COMPOSA_API_KEY);    try {      const event = await composa.webhooks.verify({        payload: await request.text(),        signature: request.headers.get('composa-signature'),        secret: env.COMPOSA_WEBHOOK_SECRET,      });      if (event.type === 'batch.completed') {        console.log(event.data.successCount, event.data.errorCount);      }      return new Response(null, { status: 204 });    } catch (error) {      if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });      throw error;    }  },};

The events are run.completed, run.failed, batch.completed, batch.failed, batch.paused, batch.expired, batch.canceled and approval.changed. Delivery is retried with the same event.id, so dedupe on it, and answer within 5 seconds.

webhooks.verify returns a promise: always await it. Event fields are in camelCase (batchId, statusUrl). event.raw is the body exactly as it arrived, with the API's snake_case names, so a field the SDK does not map yet is still reachable.

Errors

Either data is set and error is null, or the other way round:

ts
const { data, error, headers } = await composa.documents.create({  templateId: '85416813-8d99-46e8-be2b-1d61cee5db38',  data: {},});​if (error?.name === 'no_usable_value') {  for (const problem of error.problems ?? []) console.error(problem.field, problem.reason);} else if (error?.name === 'rate_limited') {  console.error(`Try again in ${error.retryAfter ?? 1} s`);} else if (error) {  console.error(error.name, error.message, headers?.['x-request-id']);} else {  console.log(`${data.content.byteLength} bytes`);}

error.name is the API's code (no_usable_value, template_not_allowed, credits_exhausted, …), or connection_error, timeout or aborted when no answer came back, and invalid_parameter when the SDK refused an argument before sending anything.

The SDK never retries by itself. The API has no idempotency key, so repeating a print prints and counts again. Retry only an answer that printed nothing: rate_limited, busy, print_busy, print_unavailable, unavailable. After a timeout or a connection_error the document may have printed.

Options

ts
const composa = new Composa('cmp_live_...', { timeoutMs: 60_000 });
OptionDefaultWhat it does
baseUrlCOMPOSA_BASE_URL, else https://api.composa.aiThe API's https:// address, with no path.
timeoutMs120000How long a call may take.
fetchthe global fetchA fetch of your own, for tests or a proxy.