Wrap your SMS provider in one small TypeScript class that owns the API key, the timeout, the retry policy and the error types, and have the rest of your app call that class. It's maybe 80 lines. It gives you one place to fix behavior, one thing to mock in tests and a clean line between "the provider refused" and "the network failed."

We make Ready, so the code uses the Ready REST API and only the request shape we document. The post doesn't depend on any SDK, because a thin wrapper of your own is often better than a heavy one anyway.

Why wrap it at all

Calling fetch in twenty places means twenty copies of the header, the timeout and the error handling, and twenty places that get the retry rule slightly different. A wrapper fixes that, and it pays off most for a platform that texts on behalf of its own customers, where a bad retry means a customer's contact gets texted twice. Our build vs buy post covers when to own more of the stack. For the plumbing, own just this layer.

Model the outcomes, not the HTTP

The caller shouldn't parse status codes. Give them a result type with the cases that need different handling:

export type SendOutcome =
  | { kind: "sent"; status: number; body: unknown }
  | { kind: "refused"; status: number; body: unknown }   // 4xx: opted out, bad number, bad input
  | { kind: "capped"; status: number; body: unknown }    // daily or monthly cap: don't loop
  | { kind: "unknown"; status: number; body: unknown } // 409 idempotency_outcome_unknown: check GET /v1/messages before resending
  | { kind: "retryable"; status: number; body: unknown } // documented not-sent 5xx: retry later with a NEW key
  | { kind: "waiting"; status: number; retryAfterMs: number } // 429, 409 still running, or a 5xx that may have sent: same key
  | { kind: "network"; error: unknown };                 // timeout, DNS, reset

export class SmsClient {
  constructor(
    private readonly apiKey: string,
    private readonly baseUrl = "https://api.tryready.com",
    private readonly maxAttempts = 4,
  ) {}

  async send(to: string, body: string, idempotencyKey: string): Promise<SendOutcome> {
    let delay = 500;
    let last: SendOutcome = { kind: "network", error: "not attempted" };
    for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
      last = await this.once(to, body, idempotencyKey);
      if (last.kind !== "network" && last.kind !== "waiting") return last;
      // Wait for Retry-After when the API sent one, else back off
      const wait = last.kind === "waiting" ? Math.max(delay, last.retryAfterMs) : delay;
      await new Promise((r) => setTimeout(r, wait));
      delay *= 2;
    }
    return last;
  }

  private async once(to: string, body: string, key: string): Promise<SendOutcome> {
    try {
      const res = await fetch(`${this.baseUrl}/v1/messages`, {
        method: "POST",
        headers: {
          "X-API-Key": this.apiKey,
          "Content-Type": "application/json",
          "Idempotency-Key": key,
        },
        body: JSON.stringify({ to, body, consent_attested: true }),
        signal: AbortSignal.timeout(15000),
      });
      const parsed = await res.json().catch(() => null);
      if (res.ok) return { kind: "sent", status: res.status, body: parsed };
      const code = (parsed as { code?: string; error?: string } | null)?.code ?? (parsed as { error?: string } | null)?.error;
      if (code === "daily_cap" || code === "number_daily_cap" || code === "monthly_cap") {
        return { kind: "capped", status: res.status, body: parsed };
      }
      if (code === "idempotency_in_progress") return { kind: "waiting", status: res.status, retryAfterMs: 3000 };
      if (res.status === 429) {
        const seconds = Number(res.headers.get("Retry-After")) || 60;
        return { kind: "waiting", status: res.status, retryAfterMs: seconds * 1000 };
      }
      if (code === "idempotency_outcome_unknown") return { kind: "unknown", status: res.status, body: parsed };
      if (code === "REQUEST_TIMEOUT_OUTCOME_UNKNOWN" || ((res.status === 502 || res.status === 503 || res.status === 504) && !code)) {
        return { kind: "waiting", status: res.status, retryAfterMs: 5000 };
      }
      if (code === "send_failed" || code === "CONTENT_REVIEW_UNAVAILABLE") return { kind: "retryable", status: res.status, body: parsed };
      return { kind: "refused", status: res.status, body: parsed };
    } catch (error) {
      return { kind: "network", error };
    }
  }
}

Callers switch on kind and TypeScript checks every case is handled. A refused result is a final answer: the number opted out, the input was bad or the send was blocked. Retrying it wastes time. A capped result is a limit that resets at midnight or on the 1st, so the client returns it at once instead of looping. An unknown result (409 idempotency_outcome_unknown) means the first request never finished, so the text may have gone out: check GET /v1/messages for the recipient before sending again with a new key. A retryable result is one the API says was not sent (send_failed or CONTENT_REVIEW_UNAVAILABLE), and the old key would replay the error, so your queue tries again later with a new key. A 504 that says the outcome is unknown, or a 502 or 503 with no JSON body, may still have sent, so the client treats it as waiting and retries with the same key. A network or waiting result that survives the retry loop goes to your queue with the same key. The exact error bodies are in the error reference.

The idempotency key is an argument, on purpose

Notice the client doesn't generate the key. If it did, two calls for the same business event would get two keys and send two texts. The caller passes a key derived from its own data, like invoice-8841-reminder-1, stored with the message record. That's the same rule described in our duplicate texts post. The one case where the same key is reused is a 429 rate limit or a 409 idempotency_in_progress: the client waits (Retry-After, or a few seconds) and sends the same key again.

Test seams

Because the app only knows SmsClient, tests inject a fake with the same send signature and assert on outcomes. For the HTTP layer itself, pass a fetch function into the constructor and stub it. Test the retry loop with a fake that returns 429 twice and then success, and assert the same idempotency key appeared on all three calls. That one test catches the most expensive bug. For safe environments to try real calls, see sandbox and test numbers.

What not to put in the client

  • Consent logic. Whether a person agreed is a business rule that lives in your database. The client only passes consent_attested, your statement.
  • Opt-out tracking. Ready refuses opted-out numbers up front, with no charge. Mirror the state for your UI with GET /v1/opt-outs/:phone, but don't build a second enforcement system.
  • Queueing. Keep the client synchronous and let a queue decide when to call it.

Cost and registration

A segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee, passed through at cost, excluding optional screening. An account can send up to 500 texts a month before it registers for 10DLC; most approvals take 2 to 7 days. See pricing.

FAQ

Should I write my own SMS client or use the provider's SDK?

Write a thin one when the API is a handful of endpoints and you want control over retries and errors. Use an SDK when it covers many endpoints you'd otherwise hand-write and it's well maintained. Either way, wrap it behind your own interface.

What should a TypeScript SMS client return on failure?

A typed result that separates refused sends, retryable failures and network errors, rather than throwing for all of them. Throwing is fine for programmer errors like a missing key.

How many retries are reasonable?

Three or four attempts with exponential backoff covers brief outages. For longer ones, hand the message to a queue with its own schedule instead of holding a request open.

The short version

One class, typed outcomes, caller-supplied idempotency keys and a retry rule you can test. Pair it with the Node.js guide for the basic request.