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
mkdir -p vendor && cp trovacast-sdk-0.4.0.tgz vendor/
npm install ./vendor/trovacast-sdk-0.4.0.tgzThe 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 withrequire(), and older versions withawait import(). - TypeScript resolves its types and its subpaths (
@trovacast/sdk/webhooks,/flows,/listenand/voice) when"moduleResolution"isnode16,nodenextorbundler. - The
trovacastcommand comes with it: see Forward events to your machine. - The changelog lists what changed in each version.
Create a client
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.
| Option | Default | What it does |
|---|---|---|
apiKey | Required | A project or integration key: tc_live_…, or tc_test_… for test mode. |
baseUrl | https://api.trovacast.com | The API origin. A trailing /v1 is accepted. |
timeoutMs | 30000 | The timeout of each attempt, in milliseconds. |
maxRetries | 2 | Retries after the first attempt, for a failure that is safe to retry. From 0 to 10. |
initialRetryDelayMs | 500 | The first backoff step. It doubles on each retry, with jitter. |
maxRetryDelayMs | 8000 | The largest backoff step. |
maxRetryAfterMs | 60000 | The longest Retry-After the client waits out. A longer one is thrown at once with retryAfterMs set, so your job queue can reschedule. |
userAgent | Not set | Your own product token, such as my-app/1.0, put before trovacast-sdk-node/<version> in the User-Agent. |
fetch | globalThis.fetch | The fetch implementation the client sends with. |
organization | Not set | For 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.
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 webhookThe 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).
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.
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.
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;
}
}| Field | What it holds |
|---|---|
status | The HTTP status, or 0 when no response arrived. |
code | The 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>. |
message | Readable text. Validation messages are joined with ; . |
requestId | The API's request id. Quote it to support. |
docUrl | The code's entry in the error reference, or null. |
retryable | Whether repeating the call later is safe and could succeed. The client has already spent its own retries when you see it. |
retryAfterMs | The server's Retry-After in milliseconds, or null. |
idempotencyKey | The key the write was sent with. Reuse it when you retry. |
idempotentReplayed | true when the API answered from its idempotency store: the outcome for that key is fixed. |
body | The parsed error body, with any extra fields the API sent. |
isNotFound | true 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,504and409 IDEMPOTENCY_KEY_IN_FLIGHT, up tomaxRetriestimes, with exponential backoff and jitter (500 ms, doubling, at most 8 s) and never sooner thanRetry-After. Only reads, and writes that carry a key, are retried. - Thrown at once: a
Retry-Afterlonger thanmaxRetryAfterMs, withretryAfterMsset for your job queue, and any error the API replayed from its idempotency store. - Replayed errors: when
idempotentReplayedistrue, 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.
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.
npx trovacast listen --forward-to http://localhost:3000/trovacast/webhook \
--events message.received,message.delivered --since 10mIt 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.
| Option | Default | What it does |
|---|---|---|
--forward-to <url> | Required | Where each event is POSTed. |
--events <a,b> | Every type | Only these event types. |
--since <duration> | Now | Also replay events from this far back, such as 10m or 2h. |
--interval <duration> | 2s | The wait between polls, at least 500ms. |
--secret <whsec_…> | A fresh whsec_listen_… | The secret forwarded events are signed with. |
--api-key <tc_…> | TROVACAST_API_KEY | The key the command polls with. |
--base-url <url> | TROVACAST_BASE_URL, then https://api.trovacast.com | The 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.
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.
const token = await trovacast.createVoiceAccessToken({
body: { identity: 'support.alice', ttlSeconds: 900, outgoing: true },
});
// Hand token.token and token.socket.url to your app.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.