Skip to content
Codelia SMSDocs
Guides: TypeScript SDK

TypeScript SDK

@codelia-studios/sms is the TypeScript client for this API. It types every request, answer and error, retries a failed request without sending twice (give each send a key of your own), pages through lists for you, and checks webhook signatures. Every call it makes is one of the endpoints in the API reference.

Install

Coming to npm

The package is being published to npm. Until it is, the install command below can't find it.

npm install @codelia-studios/sms

It needs Node.js 20 or later, or another runtime with the standard fetch and Web Crypto APIs. See Where it runs.

Create a client

The client needs your API key and your account ID, read here from the same environment variables the Quickstart sets:

create-client.ts
import { SmsClient } from "@codelia-studios/sms";

// Create one client when your app starts and share it. The key and the
// account ID come from the same environment variables the curl examples use.
export function createClient(): SmsClient {
  const apiKey = process.env.CODELIA_API_KEY;
  const accountId = process.env.CODELIA_ACCOUNT_ID;
  if (!apiKey || !accountId) {
    throw new Error("Set CODELIA_API_KEY and CODELIA_ACCOUNT_ID.");
  }
  return new SmsClient({ apiKey, accountId });
}

If the account ID isn't the key's organization, every call throws OrganizationMismatchError, which names both account IDs.

To read the account ID from the key instead, use SmsClient.fromApiKey(). It asks the API which organization the key belongs to, then builds the client for it:

from-api-key.ts
import { SmsClient } from "@codelia-studios/sms";

// Asks the API which organization the key belongs to, then builds the client
// for that organization. It makes one request, so call it once at startup.
export async function createClientFromKey(): Promise<SmsClient> {
  const apiKey = process.env.CODELIA_API_KEY;
  if (!apiKey) throw new Error("Set CODELIA_API_KEY.");
  return SmsClient.fromApiKey({ apiKey });
}

The client also takes timeoutMs, how long each attempt may take (60,000 by default); maxRetries, how many times a request may be tried again (2 by default); fetch, to use your own; and defaultHeaders, added to every request.

Keep the key on your server. Anyone who can read it can send messages with it and spend your credit.

Send a message

Price it, then send it with a key derived from your own event:

send-message.ts
import type { SmsClient } from "@codelia-studios/sms";

interface Order {
  id: string;
  phone: string;
}

export async function sendOrderReady(sms: SmsClient, order: Order) {
  const message = {
    to: [order.phone],
    from: "InfoSMS",
    body: `Your order ${order.id} is ready to collect.`,
    type: "transactional" as const,
  };

  // Price it first. Nothing is sent or charged.
  const quote = await sms.messages.quote(message);
  console.log(
    `Estimated cost: ${quote.totalMicros / 1_000_000} ${quote.currency}`,
  );

  // The key comes from the order, so calling this again for the same order
  // within 24 hours returns the first answer instead of sending a second
  // message.
  const [sent] = await sms.messages.send(message, {
    idempotencyKey: `order-${order.id}-ready`,
  });
  return sent;
}
  • send() answers with one result per number, each with its id, status and priceMicros.
  • Money is an integer number of micros: 1,000,000 micros is one unit of the currency beside it, so 31900 in EUR is €0.0319.
  • from is optional. Without it, the message goes from your organization's default sender name, and with no from and no default, sending is refused with sender_id_required. Pass from in production, so what you send doesn't depend on the default.

Every resource follows the same pattern: sms.campaigns, sms.recurringCampaigns, sms.contacts, sms.contactLists, sms.optOuts, sms.senderIds, sms.webhookEndpoints, sms.billing, sms.usage, sms.activity and sms.organization. The guides explain what each endpoint does; the SDK's types name every field.

Retry safely

These methods take an idempotencyKey in their last argument: messages.send() and messages.resend(); campaigns.send(), campaigns.cancel(), campaigns.reschedule(), campaigns.resume() and campaigns.resend(); every change to recurringCampaigns (create(), update(), pause(), resume() and delete()); and contacts.import(). On any other method the option doesn't exist, so passing one is a compile error. The SDK also exports the list, as IDEMPOTENT_OPERATIONS.

For any send you might retry, pass your own key, derived from your own event. Without one, the SDK makes a key for each call and reuses it on its own retries. That protects its retries, but if your code calls send() again, after a crash or from a job that runs twice, the new call gets a new key and sends again. Retrying safely explains what a repeat gets back.

The SDK retries a request itself, up to maxRetries times:

AnswerRetried?
429Yes, on any method, after the wait in Retry-After. A wait of more than 60 seconds throws RateLimitError, with retryAfterMs, instead.
500, 502, 503, 504, no answer, or a timeoutOnly a read (a GET, or pricing, an audience count or a list preview), or a method that takes an idempotencyKey, with the same key. Each wait is random: up to 500 ms before the first retry, doubling after that, and never more than 8 seconds. A 503 with a Retry-After of up to 60 seconds waits that long, plus up to a second, instead.
409 with idempotency_conflictFor a method that takes an idempotencyKey: yes, with the same key, after 1 second, then 2 seconds.
An answer marked Idempotency-Replayed: true, or any other errorNo.

Any other method that changes something is never retried after a 5xx or a lost answer, because a second attempt could do the work twice. If one fails that way, it may have taken effect: list what it changes before you try again.

Pass signal in the last argument to cancel a call, which stops its retries too, and timeoutMs there to change the limit for that call.

Handle errors

Every failed request throws a CodeliaError, with the HTTP status, the API's code and message, and the requestId to include when you email hello@codelia.studio. Switch on code, and keep a default branch, because new codes can be added:

handle-errors.ts
import { CodeliaError, type SmsClient } from "@codelia-studios/sms";

export async function sendReminder(sms: SmsClient, phone: string, key: string) {
  try {
    const [sent] = await sms.messages.send(
      {
        to: [phone],
        from: "InfoSMS",
        body: "Reminder: your appointment is tomorrow at 10:30.",
      },
      { idempotencyKey: key },
    );
    return { sent: true, messageId: sent?.id };
  } catch (error) {
    if (!(error instanceof CodeliaError)) throw error;
    switch (error.code) {
      case "invalid_recipient":
        // The number couldn't be matched to a country. Fix it, then send
        // again with a new key.
        return { sent: false, reason: error.code };
      case "insufficient_credits":
        // Nothing was sent. Top up in the portal, then send again with a new
        // key.
        return { sent: false, reason: error.code };
      default:
        // Keep a default: new codes can be added.
        throw error;
    }
  }
}

Or catch by class: BadRequestError (400) and its ValidationError (with fieldErrors), AuthenticationError (401), InsufficientCreditsError (402), ForbiddenError (403), NotFoundError (404) and its OrganizationMismatchError, ConflictError (409) and its IdempotencyConflictError, IdempotencyKeyReuseError (422), RateLimitError (429), ServerError (5xx), and ConnectionError and TimeoutError when no answer arrived. Errors and limits explains each code.

A campaign sent now to more than 500 people returns from campaigns.send() before it's accepted, so a problem found once it's accepted, such as a balance that doesn't cover it, doesn't throw: the campaign becomes failed, with a failureReason, and nothing is charged. Check it with campaigns.retrieve(). See Large campaigns.

When the outcome is unknown

  • TimeoutError or ConnectionError from a method that takes an idempotencyKey: no answer arrived, and the request may have taken effect. Call again with error.idempotencyKey. You get the first request's answer, or a 409 while it's still running (see IdempotencyConflictError below). Nothing is sent twice.
  • ServerError: the API answered 5xx, and it usually kept that answer, so calling again with the same key returns the same error, or IdempotencyConflictError while the first request is still running. Check whether it went through (for a message or a campaign, list your messages or campaigns), and use a new key only if it didn't. service_busy (a 503 on a GET) kept nothing; the SDK has already waited out Retry-After and retried it up to maxRetries times, so if you see it, wait and call again.
  • IdempotencyConflictError: another request with that key is still running, or didn't finish. Call again later with the same key. If it keeps failing, check before you use a new key.

Paging

list() gets one page, as the API sends it. iterate() gets every page for you:

pagination.ts
import type { ListMessagesParams, SmsClient } from "@codelia-studios/sms";

// One page, as the API sends it: up to `limit` messages, newest first, and
// the cursor for the next page (null on the last one).
export async function firstPage(sms: SmsClient) {
  const page = await sms.messages.list({ limit: 50 });
  console.log(page.entries.length, page.nextCursor);
  return page;
}

// Every page: iterate() passes nextCursor back as cursor, with the same
// filters, until it's null.
export async function everyMessageId(
  sms: SmsClient,
  filters: ListMessagesParams = {},
): Promise<string[]> {
  const ids: string[] = [];
  for await (const message of sms.messages.iterate(filters)) {
    ids.push(message.id);
  }
  return ids;
}

Messages, campaigns, recurring campaigns, contacts and the activity log page by cursor, and so does a campaign's messages, with campaigns.listMessages() and campaigns.iterateMessages(). Opt-outs and a list's members page by limit and offset. Lists, sender names and webhook endpoints come back whole, and an endpoint's deliveries as the most recent limit, so none of them has an iterate(). See Paging through results.

Import only what you use

SmsClient brings in every resource. To keep a bundle small, import the transport and one resource:

per-resource.ts
import { Core } from "@codelia-studios/sms/core";
import { Messages } from "@codelia-studios/sms/messages";

// Only the transport and the one resource you use end up in your bundle.
export function createMessages(): Messages {
  const apiKey = process.env.CODELIA_API_KEY;
  const accountId = process.env.CODELIA_ACCOUNT_ID;
  if (!apiKey || !accountId) {
    throw new Error("Set CODELIA_API_KEY and CODELIA_ACCOUNT_ID.");
  }
  return new Messages(new Core({ apiKey, accountId }));
}

@codelia-studios/sms/core holds the transport, the errors and the paging helpers. Each resource has its own entry point: messages, campaigns, recurring-campaigns, contacts, contact-lists, opt-outs, sender-ids, webhook-endpoints, billing, usage, activity and organization.

Webhooks

@codelia-studios/sms/webhooks checks a webhook request's signature. It needs no API key and doesn't load the client. This handler works in any runtime with the Fetch API's Request:

webhook-handler.ts
import {
  constructEvent,
  SIGNATURE_HEADER,
  WebhookSignatureError,
  type WebhookEvent,
} from "@codelia-studios/sms/webhooks";

// Keep this in your database in production, so a restart doesn't forget.
const handled = new Set<string>();

// For any runtime with the Fetch API's `Request` and `Response`. `secret` is
// the endpoint's signing secret, shown once when you created it, and
// `onEvent` is your own code that acts on an event.
export async function handleWebhook(
  request: Request,
  secret: string,
  onEvent: (event: WebhookEvent) => Promise<void>,
): Promise<Response> {
  let event;
  try {
    event = await constructEvent({
      secret,
      header: request.headers.get(SIGNATURE_HEADER),
      // The raw text: parsed and written out again, it no longer matches.
      body: await request.text(),
    });
  } catch (error) {
    if (error instanceof WebhookSignatureError) {
      return new Response(null, { status: 400 });
    }
    throw error;
  }

  // The same event can arrive more than once. Its id stays the same.
  if (handled.has(event.id)) return new Response(null, { status: 200 });

  // Act on the types you handle, such as "message.delivered", and ignore the
  // rest: new types can be added.
  await onEvent(event);

  // Record it only once it's handled, so a failure is tried again.
  handled.add(event.id);
  return new Response(null, { status: 200 });
}
  • Check the raw request body. A body parsed as JSON and written out again no longer matches the signature.
  • constructEvent() returns the event, { id, version, type, created, data }, or throws WebhookSignatureError.
  • verifySignature() takes the same options and returns a verdict instead: ok, missing, malformed, stale (signed more than 300 seconds from your clock) or mismatch.
  • Use event.id as your idempotency key: it's the same on every retry and replay of an event.
  • Ignore event types you don't recognize. New ones can be added.

The Webhooks guide explains the events, their data, and how to add an endpoint.

Where it runs

The SDK uses only standard web APIs, such as fetch and Web Crypto, and no Node.js-only modules. It runs on Node.js 20 or later, and on other runtimes that provide those APIs. To use your own fetch, pass it as fetch when you create the client.

Never use an API key in a browser: anyone who opens the page can read it and act as your organization. Call the API from your server.