Jump to

  • Quickstarts
  • API reference
  • Webhook events
  • Error codes
  • SDKs

Resources

Node.js SDK

Call the Trovacast API from Node.js with a typed method for every operation, retries and idempotency keys built in, pagination helpers and webhook verification.

@trovacast/sdk is the typed client for the Trovacast API on Node.js 22 or later. It is generated from the same OpenAPI contract as the API reference, so every operation is a method with typed parameters and results. It has no runtime dependencies and sends with the platform fetch.

Install

Install a package build (bash)
mkdir -p vendor && cp trovacast-sdk-0.4.0.tgz vendor/
npm install ./vendor/trovacast-sdk-0.4.0.tgz

The tarball has no runtime dependencies, so it installs offline. Commit it under its versioned name. To upgrade, add the new tarball under its own name: your lockfile records each tarball's integrity hash and refuses a changed file under a name it already knows.

  • It is an ES module: import { createTrovacastClient } from '@trovacast/sdk'. From CommonJS, Node.js 22.12 or later loads it with require(), and older versions with await import().
  • TypeScript resolves its types and its subpaths (@trovacast/sdk/webhooks, /flows, /listen and /voice) when "moduleResolution" is node16, nodenext or bundler.
  • The trovacast command comes with it: see Forward events to your machine.
  • The changelog lists what changed in each version.

Create a client

Create a client (typescript)
import { createTrovacastClient } from '@trovacast/sdk';

const trovacast = createTrovacastClient({
  apiKey: process.env.TROVACAST_API_KEY!,
});

const me = await trovacast.getMe();
console.log(me.kind, me.scopes);

getMe answers the key's kind and scopes. An apiKey that does not look like a Trovacast key (tc_…) throws a TypeError before anything is sent, which catches an unset environment variable early. The samples below use this trovacast client.

OptionDefaultWhat it does
apiKeyRequiredA project or integration key: tc_live_…, or tc_test_… for test mode.
baseUrlhttps://api.trovacast.comThe API origin. A trailing /v1 is accepted.
timeoutMs30000The timeout of each attempt, in milliseconds.
maxRetries2Retries after the first attempt, for a failure that is safe to retry. From 0 to 10.
initialRetryDelayMs500The first backoff step. It doubles on each retry, with jitter.
maxRetryDelayMs8000The largest backoff step.
maxRetryAfterMs60000The longest Retry-After the client waits out. A longer one is thrown at once with retryAfterMs set, so your job queue can reschedule.
userAgentNot setYour own product token, such as my-app/1.0, put before trovacast-sdk-node/<version> in the User-Agent.
fetchglobalThis.fetchThe fetch implementation the client sends with.
organizationNot setFor an integration key: the organization every call acts for, sent as Trovacast-Organization. The key needs organizations:act.

Every method also takes per-call options as its last argument: idempotencyKey, signal (which cancels the call and any wait between retries), timeoutMs, maxRetries and organization. A call's organization: null sends none, for your integration's own routes such as createOrganization.

Make a request

Each operation is a method named after its operationId: createMessage, listContacts, upsertContact. It takes one object with path, query and body, whichever the operation has, and resolves to the response body (undefined for a 204). In TypeScript, a missing or misspelled parameter is a compile error.

Send a WhatsApp template (typescript)
const contact = await trovacast.upsertContact(
  { body: { phone: '+919876543210', displayName: 'Aarav' } },
  { idempotencyKey: 'order-1001-contact' },
);

const message = await trovacast.createMessage(
  {
    body: {
      type: 'template',
      contactId: contact.id,
      template: { name: 'order_confirmation', language: 'en' },
      variables: { var1: 'Aarav', var2: '#1001' },
    },
  },
  { idempotencyKey: 'order-1001-confirmation' },
);
console.log(message.id, message.status); // queued; later statuses arrive by webhook

The second argument names the write's idempotency key. A key built from your order id makes the send safe to repeat: a retried job gets the first answer back instead of sending twice. The WhatsApp template quickstart walks through the whole send.

Types for every schema and operation come with the package: Contact, Message and the other common resources by name, Schemas['PublicCreateMessageDto'] for any schema, and OperationBody<'createMessage'>, OperationQuery and OperationResult by operationId.

Read the response details

trovacast.withResponse has the same methods and resolves to { data, status, headers, requestId, idempotencyKey, idempotentReplayed, rateLimit }. Use it when the status matters, as when an upsert tells a new contact (201) from an existing one (200).

Tell a new contact from an existing one (typescript)
const { data: contact, status, requestId, rateLimit } = await trovacast.withResponse.upsertContact({
  body: { phone: '+919876543210' },
});
console.log(contact.id, status === 201 ? 'created' : 'existing', requestId, rateLimit?.remaining);

rateLimit is the key's budget as of that response, { limit, remaining, resetSeconds } from the X-RateLimit-* headers, or null when they are absent. rateLimitOf(headers) reads the same from any Headers object. See Rate limits.

Paginate

paginate yields every item of a list and fetches the next page only when your loop needs it. pages yields one { data, nextCursor } page at a time. Both take the operationId and that method's arguments, and a query.cursor you pass is where the walk starts.

Every message, then every page of contacts (typescript)
for await (const message of trovacast.paginate('listMessages', { query: { contactId: 'CONTACT_ID' } })) {
  console.log(message.id, message.status);
}

for await (const page of trovacast.pages('listContacts', { query: { limit: 100 } })) {
  console.log(page.data.length, page.nextCursor);
}

The walk ends when nextCursor is null. It throws a TypeError if the API answers something that is not a page, or the same cursor twice. See Pagination.

Handle errors

Every failed call throws a TrovacastApiError. Branch on its code, which is stable; the message is written for people.

Handle a missing contact (typescript)
import { TrovacastApiError } from '@trovacast/sdk';

try {
  const contact = await trovacast.getContact({ path: { contactId: 'CONTACT_ID' } });
  console.log(contact.id);
} catch (error) {
  if (error instanceof TrovacastApiError && error.isNotFound) {
    console.log('no such contact', error.requestId);
  } else {
    throw error;
  }
}
FieldWhat it holds
statusThe HTTP status, or 0 when no response arrived.
codeThe API's code, such as CONSENT_REQUIRED or API_KEY_SCOPE_MISSING, or one the SDK sets when no answer arrived or it could not be read: NETWORK_ERROR, TIMEOUT, INVALID_RESPONSE or UNEXPECTED_REDIRECT. A proxy's answer without a code is HTTP_<status>.
messageReadable text. Validation messages are joined with ; .
requestIdThe API's request id. Quote it to support.
docUrlThe code's entry in the error reference, or null.
retryableWhether repeating the call later is safe and could succeed. The client has already spent its own retries when you see it.
retryAfterMsThe server's Retry-After in milliseconds, or null.
idempotencyKeyThe key the write was sent with. Reuse it when you retry.
idempotentReplayedtrue when the API answered from its idempotency store: the outcome for that key is fixed.
bodyThe parsed error body, with any extra fields the API sent.
isNotFoundtrue for a 404.

TROVACAST_ERROR_CODES lists every code this release knows, and isKnownErrorCode(code) tells a known code from a newer one. The API adds codes within v1, and a new one arrives as itself: read a code you do not know by its status. An error never holds the API key, a request body or a URL, so it is safe to log.

Retries and idempotency

Every write (POST, PUT, PATCH or DELETE) carries an Idempotency-Key. By default the client mints a fresh UUID for each call and sends the same key on every retry of that call, so a retry whose first attempt landed gets the stored answer instead of running twice. Pass your own key, 1 to 255 visible ASCII characters, to make a write safe across processes and restarts too. { idempotencyKey: false } sends none, and that write is then never retried.

  • Retried: a timeout, a network error, 429, 500, 502, 503, 504 and 409 IDEMPOTENCY_KEY_IN_FLIGHT, up to maxRetries times, with exponential backoff and jitter (500 ms, doubling, at most 8 s) and never sooner than Retry-After. Only reads, and writes that carry a key, are retried.
  • Thrown at once: a Retry-After longer than maxRetryAfterMs, with retryAfterMs set for your job queue, and any error the API replayed from its idempotency store.
  • Replayed errors: when idempotentReplayed is true, every retry with that key gets the same answer. Read the resource to see whether the first attempt took effect, and only if it did not, send the write again with a new key.
  • A redirect is never followed, so the key never travels to another URL.

Idempotency explains what the API stores against a key, and for how long.

Verify webhooks

Verify the raw body before you parse it. constructWebhookEvent checks the Trovacast-Signature header against every secret you pass, in constant time and within 300 seconds, and returns the typed event. A delivery that fails throws TrovacastWebhookError, whose reason says why: SIGNATURE_MISSING, TIMESTAMP_OUT_OF_TOLERANCE, SIGNATURE_MISMATCH or PAYLOAD_INVALID. Answer it with 400.

Verify a delivery in Express (typescript)
import express from 'express';
import { constructWebhookEvent, TrovacastWebhookError } from '@trovacast/sdk/webhooks';

const app = express();

app.post('/trovacast/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = constructWebhookEvent({
      payload: req.body, // the raw Buffer
      header: req.headers['trovacast-signature'],
      secrets: [process.env.TROVACAST_WEBHOOK_SECRET!],
    });
  } catch (error) {
    if (!(error instanceof TrovacastWebhookError)) throw error;
    res.sendStatus(400);
    return;
  }
  // Deliveries arrive at least once: deduplicate on event.id.
  if (event.type === 'message.delivered') console.log(event.data.message.id);
  res.sendStatus(204);
});

app.listen(3000);

@trovacast/sdk/webhooks holds only the webhook half of the package, for a receiver that never calls the API; the package root exports the same functions. verifyWebhookSignature takes the same input and returns true or false, toleranceSeconds changes the 300-second window, and in your own tests createWebhookSignatureHeader({ payload, secret }) signs a delivery. The scheme itself is described under Webhooks.

Rotate a secret

After you rotate an endpoint's secret, every delivery for the next 24 hours carries a second v1 signature made with the previous secret. A delivery is genuine when any signature matches any secret you pass, so list both while you deploy the new one: secrets: [current, previous]. A missing or empty secret throws a TypeError, since anyone could compute a signature with an empty key.

Forward events to your machine

The package's trovacast command forwards your project's webhook events to a handler on your machine while you build it. It polls GET /v1/events and POSTs each new event's envelope to your URL, oldest first and once each.

Forward events to a local handler (bash)
npx trovacast listen --forward-to http://localhost:3000/trovacast/webhook \
  --events message.received,message.delivered --since 10m

It reads the key from TROVACAST_API_KEY, and the key needs webhooks:manage and the read scope of each event it forwards. Once the package is on npm, npx @trovacast/sdk listen … runs it without an install.

At start it prints a local signing secret, whsec_listen_…, and signs every forwarded event with it: the API returns an endpoint's own secret only when you create or rotate it, so the forwarder never holds that secret. Point your handler's verifier at the printed secret while it runs behind the forwarder, and deploy with your endpoint's real secret.

OptionDefaultWhat it does
--forward-to <url>RequiredWhere each event is POSTed.
--events <a,b>Every typeOnly these event types.
--since <duration>NowAlso replay events from this far back, such as 10m or 2h.
--interval <duration>2sThe wait between polls, at least 500ms.
--secret <whsec_…>A fresh whsec_listen_…The secret forwarded events are signed with.
--api-key <tc_…>TROVACAST_API_KEYThe key the command polls with.
--base-url <url>TROVACAST_BASE_URL, then https://api.trovacast.comThe API origin.

The API records an event only when an endpoint of your project subscribes to its type, and a disabled endpoint counts. If you have none, create a disabled endpoint for the types you are working on. A handler that answers with a non-2xx status, or is not running, is reported and skipped: restart with --since to replay.

Build call flows

callFlow() builds a stored call flow and answer() the document an answer URL returns, one chained method per verb. toJSON() checks the document as the API will and throws CallFlowValidationError, whose issues give each problem's path and message. @trovacast/sdk/flows exports the builders without the HTTP client, for an answer-URL server.

Build an IVR and store it (typescript)
import { callFlow, node, verbs } from '@trovacast/sdk/flows';

const definition = callFlow({ start: 'main' })
  .node('main', (n) =>
    n.menu({
      prompt: [verbs.say('Press 1 for sales, 2 for support.')],
      options: { '1': node('sales'), '2': node('support') },
    }),
  )
  .node('sales', (n) => n.connect({ number: '+918031150000' }))
  .node('support', (n) => n.say('Please call back in office hours.').hangup())
  .toJSON();

const flow = await trovacast.createCallFlow({ body: { name: 'Main menu', definition } });
console.log(flow.id);

validate() returns { ok, issues } instead of throwing, and validateCallFlow(document) checks a document built any other way. The API still checks what only it can, such as whether the queues and numbers a flow names are your project's.

Calls in your own app

@trovacast/sdk/voice lets a browser place and answer calls as one identity of your app. Your server mints a short-lived token with createVoiceAccessToken (scope voice:client, and calls:write as well for outgoing), and the app connects with that token, so the API key stays on your server.

Mint a token on your server (typescript)
const token = await trovacast.createVoiceAccessToken({
  body: { identity: 'support.alice', ttlSeconds: 900, outgoing: true },
});
// Hand token.token and token.socket.url to your app.
Place a call from the browser (typescript)
import { VoiceDevice } from '@trovacast/sdk/voice';

// Your own server's route, answering the token and socket URL it minted.
const { token, socketUrl } = await (await fetch('/voice-token')).json();

const device = new VoiceDevice(token, { url: socketUrl });
await device.connect();
device.on('incoming', (call) => void call.accept());

const call = await device.call({ to: { phone: '+919812345678' } });
call.on('disconnect', (reason) => console.log('ended:', reason));

Audio travels over the socket as 16-bit PCM at 8, 16 or 24 kHz. In a browser the default audio uses the microphone and Web Audio; anywhere else, pass a WebSocket implementation and your own audio. When the device emits tokenWillExpire, mint a new token and pass it to device.updateToken(…). The reference lists the token's options.

Next steps