Node.jsMenu
On this page

Node.js

Integrate with the Kirora API using the Node.js library: typed requests, pagination, retries and webhook verification.

View as MarkdownOpen in ClaudeOpen in ChatGPTUpdated

Use @kirora/node to call the Kirora /v1 API from a Node.js server with typed requests, pagination, retry handling and webhook verification. The TypeScript library is the reference implementation for other server clients. This page covers the common tasks; the README is the full reference.

Install

Install @kirora/node from npm:

Terminal
npm install @kirora/node

It needs Node.js 22 or later, has no runtime dependencies, and is ES modules only: load it with import, not require().

Create a client

Keep your API key on your server and set it as KIRORA_API_KEY; the client reads it from there:

TypeScript
import { Kirora } from '@kirora/node';

const kirora = new Kirora(); // reads KIRORA_API_KEY
Option Type Default Description
apiKey string KIRORA_API_KEY Your API key (kirora_…). The constructor throws if there’s none.
baseUrl string https://api.kirora.io For tests and mocks. The host only, without a version: the client adds /v1 to each path.
timeoutMs number 30000 How long each attempt may take, including reading the response.
retry.maxRetries number 3 Attempts after the first, from 0 to 10. 0 disables retrying.
retry.maxDelayMs number 30000 Ceiling for a single backoff wait. A longer Retry-After is returned to you instead of waited out.
fetch typeof fetch globalThis.fetch Inject a proxy-aware implementation, or a stub in tests.
workspace string None Partner keys only: the tenant workspace’s externalId. See Partner workspaces.

Method names are the operationId with the resource dropped, so identifyContact is kirora.contacts.identify() and sendCampaign is kirora.campaigns.send(). Methods return the response’s data, already unwrapped.

Namespace Methods
contacts list, get, update, delete, identify, identifyBatch, deleteBatch, merge, export, listLists, listTopics, setTopic, listInstallations, registerInstallation, deleteInstallation
lists list, get, create, update, delete, addContacts, deleteContacts
campaigns list, get, create, send, trigger, schedule, eligibility
transactional send, sendBatch, cancel
events track, trackBatch
messages list, get
suppressions list, add, delete
workspaces list, create, get, update, delete, suspend, resume, cancelDeletion (partner keys only)
embedSessions create (partner keys only)

On the client itself, kirora.me() returns the API key in use, its scopes and the workspace it acts in, and kirora.forWorkspace(externalId) returns a copy that acts in one of your tenants.

Methods that take a contact id also take { idType: 'externalId' } or { idType: 'email' } to look the contact up by those, as in kirora.contacts.get('[email protected]', { idType: 'email' }).

For an operation without a method, call the transport directly with kirora.client.request(method, path, options), or kirora.client.list(path, options) for a list; both use the same auth, retries and error mapping. The exported components and operations types cover only the operations with methods, so give request<T>() your own result type.

Identify a contact

contacts.identify() calls identifyContact: an upsert resolved by externalId, then email, then phone. It is safe to repeat; it converges rather than creating duplicates.

TypeScript
const contact = await kirora.contacts.identify({
  externalId: 'cust_1042',
  email: '[email protected]',
  firstName: 'Olivia',
  attributes: { plan: 'weekly-box', city: 'Toronto' },
});

console.log(contact.id);

Track an event

events.track(body, { idempotencyKey }) calls trackEvent. The key is optional; pass one derived from your own event or order id to make your own retries safe too. Without one, the library makes one per call, which covers only its own retries.

TypeScript
const event = await kirora.events.track(
  {
    externalId: 'cust_1042',
    name: 'Order Completed',
    properties: { order_id: '1042', total: 42.5, currency: 'USD' },
  },
  { idempotencyKey: 'order-1042-completed' },
);

console.log(event.id, event.occurredAt);

Send a transactional message

transactional.send(body, { idempotencyKey }) calls sendTransactionalMessage. The key is optional, but pass your own, made once per logical send before the first attempt and outside any retry loop: a retry with the same key and body then replays the first send for as long as its message is kept (Retention). Without one, the library makes one per call, which covers only its own retries. See Idempotency.

TypeScript
const orderId = '1042';

const { messages, skippedChannels, skippedCopies } = await kirora.transactional.send(
  {
    to: { email: '[email protected]' },
    data: { order_id: orderId },
    email: {
      template: 'order-receipt', // its alias or its id
      subject: 'Your Juniper Kitchen receipt',
      from: 'Juniper Kitchen <[email protected]>',
    },
  },
  { idempotencyKey: `receipt-${orderId}` },
);

for (const message of messages) {
  console.log(message.id, message.channel, message.status);
}

A successful send can still leave a channel unsent, such as push for a contact with no device: each is in skippedChannels. A cc or bcc address that got no copy, such as a suppressed one, is in skippedCopies.

transactional.sendBatch(body) calls sendTransactionalMessagesBatch: up to 100 messages, each with its own idempotencyKey in the body. An entry without one gets one before the first attempt, so a retried batch replays it rather than sending it again. transactional.cancel(messageId) cancels a message scheduled with sendAt.

Paginate

Every list(), including nested ones such as contacts.listLists(contactId), works two ways. Iterate over it with for await for every item: it follows the cursor for you, fetching pages as you go, and stops when nextCursor is null.

TypeScript
for await (const contact of kirora.contacts.list({ limit: 100 })) {
  console.log(contact.email);
}

Or await it for one page. To fetch the next page yourself, pass meta.pagination.nextCursor back as cursor, with the same filters. Treat the cursor as opaque.

TypeScript
const page = await kirora.contacts.list({ limit: 100 });
console.log(page.data.length, page.meta.pagination.nextCursor);

if (page.meta.pagination.nextCursor !== null) {
  const next = await kirora.contacts.list({
    limit: 100,
    cursor: page.meta.pagination.nextCursor,
  });
}

See Pagination.

Errors

Every error the API returns is a KiroraError. Branch on code, never on message.

TypeScript
import { KiroraError, KiroraConnectionError } from '@kirora/node';

try {
  await kirora.campaigns.send(campaignId);
} catch (error) {
  if (error instanceof KiroraError && error.code === 'SENDING_DOMAIN_UNVERIFIED') {
    // Recoverable: publish the DNS records and check the domain.
  } else if (error instanceof KiroraConnectionError) {
    // No complete response: network failure or timeout, after retries.
  }
  throw error;
}
Property Description
code The API’s error code, typed as the published catalogue or any string, so a code added after your build never crashes the client.
message Human-readable; for logs, not for branching.
status The HTTP status.
errors On VALIDATION_ERROR and DRAFT_INCOMPLETE, each field the request got wrong, as { field, message } pairs to show beside a form input.
details What else the code reports, such as the limit a PLAN_LIMIT_REACHED hit. Its shape depends on the code; see Errors.
requestId The X-Request-Id response header, for support.
retryAfterSeconds The Retry-After header, when the server sent one.
isRetryable true for 429 and 5xx.
isKnownCode() false for a code published after this build.

The full code catalogue is exported as ERROR_CODES. Other failures throw other errors:

  • KiroraConnectionError: no complete response, such as a connection reset, or the connection dropping while the body was read. The original error is on cause.
  • KiroraTimeoutError: an attempt took longer than timeoutMs. It is a subclass of KiroraConnectionError.
  • KiroraResponseError: a success status with a body the library can’t use, such as HTML from a proxy. It has status and requestId.

Retries and timeouts

Every request goes through one retry loop, which repeats a call only when repeating it is safe:

  • 429 is always retried: the server refused it before doing anything.
  • 5xx and connection failures (including timeouts) are retried only when a repeat is deduplicated or lands on the same result:
    • reads and DELETEs
    • calls with an idempotency key. events.track, transactional.send, transactional.cancel, campaigns.create, campaigns.send, campaigns.trigger, lists.create, contacts.merge, embedSessions.create and the workspaces calls create, suspend, resume and cancelDeletion use yours, or make one per call (see Idempotency)
    • the batch calls, transactional.sendBatch and events.trackBatch, since every entry carries its own idempotency key
    • calls that converge on the same result, such as contacts.identify, contacts.update, contacts.setTopic, lists.update, lists.addContacts, campaigns.schedule and suppressions.add
  • Other 4xx errors are never retried, including the 409s an idempotency key can return, such as IDEMPOTENCY_KEY_IN_USE.
  • Backoff: exponential (1 s, 2 s, 4 s…) with ±25% jitter, capped at retry.maxDelayMs. When the server sends Retry-After, the retry never comes sooner. If Retry-After is longer than retry.maxDelayMs, the client doesn’t wait: the error goes to you, with retryAfterSeconds set.
  • Bounded: at most retry.maxRetries retries (default 3), then the last error is thrown. A retry sends the same body and idempotency key as the first attempt.
  • Timeout: timeoutMs (default 30 s) applies to each attempt, so a call that retries can take longer in total. For an overall deadline, pass a signal such as AbortSignal.timeout().

Per-call options

Every method takes an optional last argument:

Option Description
signal Cancels the call, including a wait before a retry. A cancelled call rejects with the signal’s reason and is never retried.
workspace Partner keys only: the tenant to act in for this call.
timeoutMs, maxRetries Override the client’s settings for this call.
idempotencyKey On methods that create, send or record something.
TypeScript
const controller = new AbortController();

for await (const contact of kirora.contacts.list({}, { signal: controller.signal })) {
  // controller.abort() stops the iteration
}

Results, and pages from an awaited list(), carry the HTTP response they came from as lastResponse: its status, headers, requestId, and idempotencyReplay, which is true when an earlier request with the same key already did the work and this is its stored response. It’s left out of JSON and spreads.

TypeScript
const contact = await kirora.contacts.get(contactId);
console.log(contact.lastResponse.requestId); // quote this to Kirora support

Verify webhooks

verifyWebhookSignature(secret, rawBody, signature, timestamp) checks the X-Webhook-Signature header (sha256= plus the HMAC-SHA256 of ${timestamp}.${rawBody}) in constant time, rejects a timestamp more than 300 seconds from now, and accepts any of the comma-separated signatures sent while a secret rotation overlaps. readWebhookHeaders(headers) takes Node’s req.headers or a fetch Headers and pulls out the X-Webhook-* headers. It returns undefined if a required one is missing, empty or malformed, including an attempt that isn’t a whole number.

Verify against the raw body, before parsing. Parsing JSON and re-serializing it changes the bytes and the signature will not match. With Express, use express.raw() on the webhook route:

TypeScript
import express from 'express';
import { readWebhookHeaders, verifyWebhookSignature } from '@kirora/node';

const app = express();

app.post('/webhooks/kirora', express.raw({ type: 'application/json' }), (req, res) => {
  const headers = readWebhookHeaders(req.headers);
  if (
    !headers ||
    !verifyWebhookSignature(
      process.env.KIRORA_WEBHOOK_SECRET!,
      req.body, // a Buffer, because of express.raw()
      headers.signature,
      headers.timestamp,
    )
  ) {
    return res.status(401).end();
  }

  // Delivery is at-least-once: deduplicate on headers.eventId.
  const payload = JSON.parse(req.body.toString('utf8'));
  console.log(headers.event, headers.eventId, headers.attempt, payload);
  res.status(200).end();
});

With a fetch-style handler, such as a Next.js route, read the body with text():

TypeScript
import { readWebhookHeaders, verifyWebhookSignature } from '@kirora/node';

export async function POST(request: Request) {
  const rawBody = await request.text();
  const headers = readWebhookHeaders(request.headers);
  if (
    !headers ||
    !verifyWebhookSignature(
      process.env.KIRORA_WEBHOOK_SECRET!,
      rawBody,
      headers.signature,
      headers.timestamp,
    )
  ) {
    return new Response(null, { status: 401 });
  }

  const payload = JSON.parse(rawBody);
  return new Response(null, { status: 200 });
}

Pass { toleranceSeconds } as a fifth argument to change the replay window. To find out why a webhook failed, call assertWebhookSignature() instead: it throws a KiroraWebhookVerificationError with a reason. WEBHOOK_EVENTS lists the event types known at build time; treat the type as open, because a * subscription receives types added later. See Webhooks.

Partner workspaces

With a partner key, act in one of your tenants’ workspaces by its externalId, with kirora.forWorkspace(), the client’s workspace option, or a call’s own workspace option. Each is sent as the Kirora-Workspace header; a call’s option overrides the client’s.

TypeScript
const tenant = kirora.forWorkspace('tenant-42');
await tenant.contacts.get(contactId);

Manage the workspaces themselves with kirora.workspaces. delete() takes effect after a grace period, which cancelDeletion() stops.

TypeScript
await kirora.workspaces.create({ name: 'Acme', externalId: 'tenant-42', country: 'GB' });

To embed Kirora’s segment or email builder in your app, create a session for the tenant on your server and give its token to the browser. A session lasts 15 minutes.

TypeScript
const session = await kirora
  .forWorkspace('tenant-42')
  .embedSessions.create({ components: ['email_builder'] });

Sign tokens for the web SDK

The web SDK signs users in with a token from your server. createUserToken(secret, userId) signs one:

TypeScript
import { createUserToken } from '@kirora/node';

const token = createUserToken(process.env.KIRORA_SDK_TOKEN_SECRET!, user.id);

secret is the workspace’s SDK token secret, from Developer → SDK in the dashboard; it never leaves your server. userId is your own id for the user, their contact’s externalId. The token is valid for an hour; pass { expiresInSeconds } as a third argument to change that, up to Kirora’s limit of 24 hours. It needs no client and no API key. The web SDK’s setup has the whole route, for Express and Next.js.