Skip to content

Node.js SDK

@printsluis/client is the Node.js and TypeScript client for the Printsluis API (/v1). It submits print jobs, follows their status, lists printers, aliases and agents, manages webhooks and partner organizations, encrypts documents end to end, and verifies webhooks. It does what the .NET SDK does, with the same defaults.

  • Node.js 22 or later; ESM and CommonJS, with TypeScript types.
  • No runtime dependencies: HTTP is fetch, encryption is node:crypto.
  • MIT licensed.
Terminal window
npm install @printsluis/client
import { PrintsluisClient } from "@printsluis/client";
const printsluis = new PrintsluisClient({ apiKey: process.env.PRINTSLUIS_API_KEY! });
  • apiKey is an API key of your organization, from the portal’s API keys page. Keep it in a secret store or an environment variable, not in source control.
  • Create the client once and reuse it: it caches the agents’ encryption keys.
  • timeoutMs is 30 000 per attempt by default. baseUrl is https://api.printsluis.nl/ by default.
  • headers adds headers to every request, such as your application’s User-Agent.
  • integration is for store integrations only: it sends X-Printsluis-Integration (such as zapier) with every request. See Integrations. Unset by default.
  • me() returns the API key’s kind, name, scopes and organization, for example as a connection test.
  • fetch replaces the global fetch, for example for a proxy agent or in tests.

Documents are encrypted end to end by default.

import { PrintDocuments, PrintTargets } from "@printsluis/client";
const job = await printsluis.print(
{
target: PrintTargets.byPrinter(user.printerId, "labels"),
document: PrintDocuments.zpl("^XA^FO50,50^A0N,40,40^FDHello from Printsluis^FS^XZ"),
copies: 1,
externalReference: `order-${order.id}`,
},
{ idempotencyKey: `order-${order.id}-label` },
);
  • PrintDocuments.zpl(text or bytes), PrintDocuments.pdf(bytes) and PrintDocuments.raw(bytes) base64-encode the content. A plain object { format, content } with base64 content works too.
  • PrintTargets.byPrinter(printerId, fallbackAlias?) and PrintTargets.byAlias(alias) build the target.
  • Always pass an idempotencyKey when a request may be retried: the same key returns the same job instead of printing twice. See Idempotency keys.
  • printOptions (paper size, tray, duplex, …) and metadata are as in the API reference.

The request and response types come from the API’s OpenAPI document, so they match the API reference. Dates are ISO 8601 strings, as in the JSON.

const current = await printsluis.getJob(job.id);
for (const step of current.events ?? []) console.log(step.at, step.from, "->", step.to, step.detail);
const failed = await printsluis.searchJobs({ status: "failed", createdFrom: new Date(Date.now() - 86_400_000) });
await printsluis.cancelJob(job.id);

Also testPrint(printerId), listPrinters({ format, enabledOnly }), getPrinter(printerId), listAliases(), listAgents() and listAlerts(). Rather than polling, let Printsluis call you: see Webhooks.

Every method takes an optional { signal } last, an AbortSignal that cancels the call, including a wait after a 429.

A rejected request throws PrintsluisError. Its code, such as printer_unavailable, job_not_cancellable or idempotency_key_reused, is stable and safe to branch on; status is the HTTP status. Without a problem code it is http_<status>.

import { PrintsluisError } from "@printsluis/client";
try {
await printsluis.print(request, { idempotencyKey });
} catch (error) {
if (error instanceof PrintsluisError && error.code === "printer_unavailable") {
// No enabled printer that accepts the format matches the target: let the user choose another printer.
} else throw error;
}

The common codes are in Concepts; the encryption codes are below. Network errors and timeouts are thrown as fetch throws them.

When Printsluis answers 429 Too Many Requests, the client waits as long as Retry-After says and sends the same request again, with the same idempotency key. A request answered with 429 was not processed, so a retry never prints twice. The defaults are those of the .NET SDK:

new PrintsluisClient({
apiKey,
rateLimitRetry: { enabled: true, maxRetries: 3, maxTotalWaitMs: 30_000, fallbackDelayMs: 1_000 },
});

When Retry-After asks for longer than what is left of maxTotalWaitMs, or after the last retry, the client throws PrintsluisError with status 429. Set enabled: false to get the 429 at once. The limits are in Concepts.

print encrypts every document so that only the agents that can print it can read it, as the .NET SDK does:

  1. It fetches the encryption keys of the agents that can print the target, and caches them for 5 minutes per target.
  2. It drops every key that is not signed by its agent’s identity key and, when you pin agents, every key of an agent you don’t trust.
  3. It encrypts the document for the remaining agents and submits it. The job’s encrypted is true.

It never falls back to sending the document unencrypted: with no key left, it throws before anything is submitted. When an agent replaced its key since the keys were fetched, it fetches them again and retries once, with the same idempotency key.

new PrintsluisClient({
apiKey,
encryption: {
mode: "required", // the default; "off" sends documents unencrypted
trustedAgents: ["SHA256:A5BYxvLAy0ksUzsKTRTvd8wPeKvMztUofYShogEc+4E"], // optional pinning
includeFailoverPrinters: false, // the default
},
});
  • trustedAgents: only encrypt for these agents. Get each fingerprint on the agent’s own machine (pair or diagnose), not from the portal. See Pinning agents. An entry that is not a fingerprint throws when the client is created.
  • includeFailoverPrinters: also encrypt for the agents of an alias’s failover printers, so a waiting job can move to them. Each agent adds 145 bytes.
  • mode: "off" sends documents unencrypted, for example while agents are being updated. A document with encrypted: true is always sent as it is.

getEncryptionKeys(target) returns the keys as Printsluis hands them out, unverified, for example to show the agents’ fingerprints in an admin screen:

import { fingerprint } from "@printsluis/client";
const { keys } = await printsluis.getEncryptionKeys({ alias: "labels" });
for (const key of keys) console.log(key.agentId, fingerprint(Buffer.from(key.identityKey, "base64")));
Code Meaning What to do
encryption_unavailable No agent that can print the target has an encryption key, or none is signed by its agent. Thrown before submitting. Update the agents; check the target.
encryption_untrusted None of the agents is in trustedAgents. The message lists their IDs and fingerprints. Thrown before submitting. Compare a fingerprint with diagnose on the agent’s machine, then add it.
encryption_keys_stale The keys changed and still did after one retry. Retry later; with pinning, check that every agent of the target is trusted.
encryption_required The organization only accepts encrypted documents and mode is "off". Turn encryption on.

Verify the raw body before you parse it, then switch on the event type. With Express:

import express from "express";
import { parseWebhookEvent, verifyWebhookSignature, webhookHeaders } from "@printsluis/client";
app.post("/webhooks/printsluis", express.raw({ type: "application/json" }), async (req, res) => {
if (!verifyWebhookSignature(process.env.PRINTSLUIS_WEBHOOK_SECRET!,
req.get(webhookHeaders.timestamp), req.body, req.get(webhookHeaders.signature)))
return res.sendStatus(401);
const event = parseWebhookEvent(req.body);
switch (event.type) {
case "print_job.finished": // print_job.failed carries the same data, for failed, expired and indeterminate jobs
await jobs.complete(event.data.jobId, event.data.status);
break;
case "printer.needs_attention":
case "printer.unreachable":
case "printer.ready":
await printers.show(event.data.printerId, event.data.availability, event.data.availabilityDetail);
break;
default: // other and newer event types: ignore them
break;
}
res.sendStatus(200);
});

verifyWebhookSignature checks the signature in constant time against each signature in the header (two during a secret rotation) and rejects requests more than 5 minutes old. Deliveries can repeat (ignore a known id) and arrive out of order (compare createdAt). See Webhooks.

To manage endpoints with a key with webhooks:manage: createWebhook, listWebhooks, getWebhook, updateWebhook, rotateWebhookSecret and deleteWebhook. createWebhook and rotateWebhookSecret return the secret only once.

With a partner’s API key, printsluis.organizations creates and manages customer organizations (create, get, findByExternalReference, list, update, delete), their pairing codes (createPairingCode) and API keys (listApiKeys, createApiKey, revokeApiKey), and getUsage(year, month) lists the active ones. To act inside a customer organization, use forOrganization, which sends X-Organization-Id with every request:

const customer = await printsluis.organizations.findByExternalReference("customer-42");
await printsluis.forOrganization(customer!.id).print(request, { idempotencyKey });

The SDK follows semantic versioning, with the same promises as the .NET SDK: within a major version the API only grows and the behavior and defaults stay. Enum values, problem codes and webhook event types may get new values in a minor release: handle unknown ones. Dropping a Node.js major that is no longer supported is a minor release.