# TypeScript SDK

- Page: https://bytesms.com/docs/sdk (markdown: https://bytesms.com/docs/sdk.md)
- API base URL: https://api.bytesms.com/api (public resources under /api/v1)
- Auth: `Authorization: Bearer tp_live_…` — an API key from Dashboard → API Keys; keep it server-side (e.g. `BYTESMS_API_KEY`)
- All docs in one file: https://bytesms.com/llms-full.txt · OpenAPI 3.1: https://bytesms.com/openapi.json

Use the official @bytesms/sdk package for TypeScript and JavaScript: install, client options, sending, { data, error } results, idempotency, retries and webhook verification.

`@bytesms/sdk` is the official SDK for TypeScript and JavaScript. It has no runtime dependencies and uses the global `fetch`, so it runs on Node.js 18+, Bun, Deno, Cloudflare Workers, Vercel Edge and other fetch-based runtimes. It ships ESM and CommonJS builds with TypeScript types. Package page: [npmjs.com/package/@bytesms/sdk](https://www.npmjs.com/package/@bytesms/sdk).

## Install

**npm**

```bash
npm install @bytesms/sdk
```

**pnpm**

```bash
pnpm add @bytesms/sdk
```

**yarn**

```bash
yarn add @bytesms/sdk
```

**bun**

```bash
bun add @bytesms/sdk
```

## Send an email

Create an API key under **Dashboard → API Keys** (see [Authentication](https://bytesms.com/docs/authentication)). Until you [verify a domain](https://bytesms.com/docs/domains), send from `onboarding@mail.bytesms.com` to your own account email or a `@test.bytesms.com` test address.

**TypeScript**

```ts
import { Bytesms } from "@bytesms/sdk";

const bytesms = new Bytesms(process.env.BYTESMS_API_KEY); // or new Bytesms() to read BYTESMS_API_KEY

const { data, error } = await bytesms.emails.send({
  from: "Acme <hello@example.com>",
  to: "customer@example.com",
  subject: "Welcome to Acme",
  html: "<p>Thanks for signing up.</p>",
});

if (error) {
  console.error(error.name, error.message);
} else {
  console.log(data.id);
}
```

CommonJS works too: `const { Bytesms } = require("@bytesms/sdk");`. Field names match the REST API (snake_case, such as `reply_to` and `scheduled_at`), so the [Emails](https://bytesms.com/docs/emails) reference applies as written.

> **Warning: Keep keys on the server**
>
> Never put an API key in browser or mobile app code. Call the SDK from your backend, a route handler or a worker.

## Client options

`new Bytesms(apiKey?, options?)`. Without an `apiKey` argument the client reads the `BYTESMS_API_KEY` environment variable.

**Client options**

- `baseUrl` (string, optional, default `https://api.bytesms.com/api`): API origin including `/api`. The `BYTESMS_BASE_URL` environment variable is used when this is not set.
- `timeoutMs` (number, optional, default `30000`): Timeout per attempt, in milliseconds.
- `maxRetries` (number, optional, default `2`): Extra attempts after the first one for retryable failures (see [Retries](https://bytesms.com/docs/sdk#retries)). `0` turns retries off.
- `fetch` (function, optional): Custom `fetch` implementation (tests, proxies).
- `headers` (object, optional): Extra headers sent with every request.

**Per-call options**

- `idempotencyKey` (string, optional): Sent as the `Idempotency-Key` header on `emails.send` and `emails.batch`, 1 to 256 characters.
- `signal` (AbortSignal, optional): Cancels the request and any pending retry.
- `timeoutMs` (number, optional): Overrides the client timeout for this call.
- `maxRetries` (number, optional): Overrides the client retry count for this call.
- `headers` (object, optional): Extra headers for this call.

**TypeScript**

```ts
const bytesms = new Bytesms(process.env.BYTESMS_API_KEY, {
  baseUrl: "https://api.bytesms.com/api", // default
  timeoutMs: 30_000,
  maxRetries: 2,
  headers: { "X-Request-Source": "billing-worker" },
});

// Per-call options: the last argument of every method
await bytesms.emails.send(email, {
  idempotencyKey: "welcome-user-123",
  signal: abortController.signal,
  timeoutMs: 10_000,
  maxRetries: 5,
});
```

## Responses and errors

Every method resolves to `{ data, error, headers }` and does not throw on API or network errors. Exactly one of `data` and `error` is set. `headers` holds the response headers in lower case (for example `ratelimit-remaining`), or `null` when no response was received.

**TypeScript**

```ts
const { data, error, headers } = await bytesms.emails.send(email);

if (error) {
  switch (error.name) {
    case "validation_error":       // 422: fix the request
    case "invalid_from_address":   // 403: the from domain is not verified in this workspace
      break;
    case "daily_quota_exceeded":   // 429: plan limits, see error.code / error.limit / error.current
    case "monthly_quota_exceeded":
      break;
    case "insufficient_credits":   // 402: see error.neededThb / error.availableThb
      break;
    case "rate_limit_exceeded":    // 429: still limited after the automatic retries
      break;
    case "network_error":          // no response (statusCode: null)
    case "timeout_error":
      break;
  }
} else {
  console.log(data.id, headers["ratelimit-remaining"]);
}
```

| Field | Notes |
| --- | --- |
| `name` | The API's error name (see [Errors](https://bytesms.com/docs/errors)), or a client-side name: `missing_api_key`, `network_error`, `timeout_error`, `aborted`, `invalid_response`. |
| `message` | Human-readable text. Don't branch on it. |
| `statusCode` | HTTP status, or `null` when no response was received. |
| `code, limit, current` | Present on quota and plan-limit errors, when the API sends them. |
| `neededThb, availableThb` | Present on `insufficient_credits`. |

The only method that throws is `webhooks.verify`, which throws `WebhookVerificationError` for a request that is not authentic (see [Webhooks](https://bytesms.com/docs/sdk#webhooks)).

## Idempotency

Pass `idempotencyKey` to `emails.send` or `emails.batch`. Bytesms accepts the email once and returns the original response to every retry with the same key for 24 hours; the same key with a different body is `409 idempotency_key_conflict`. Derive the key from your own data (an order id, a user id plus an event) so a job that runs twice reuses it. Details: [Idempotency](https://bytesms.com/docs/idempotency).

**TypeScript**

```ts
const { data, error } = await bytesms.emails.send(
  { from: "Acme <billing@example.com>", to: user.email, subject: "Receipt", html },
  { idempotencyKey: `receipt-${order.id}` },
);
```

## Retries

The SDK retries up to `maxRetries` times with exponential backoff and jitter, and waits for the `Retry-After` header when the response has one (capped at 60 seconds per wait). It retries:

- `429 rate_limit_exceeded`, the per-second request limit (see [Rate limits](https://bytesms.com/docs/rate-limits)),
- `5xx` responses,
- network errors and timeouts.

So that an email is never sent twice, a `POST` without an `idempotencyKey` is retried only when nothing reached the API: the connection failed before the request was sent (for example connection refused or a DNS failure), or the response was `429 rate_limit_exceeded`, which the API returns before doing any work. A `5xx` or a timeout on such a `POST` is returned to you without a retry. `GET`, `PATCH` and `DELETE` requests, and a `POST` with an `idempotencyKey`, are retried in all the cases above. Quota errors (`daily_quota_exceeded`, `monthly_quota_exceeded`) and other `4xx` errors are never retried.

## Webhooks

`bytesms.webhooks.verify(rawBody, headers, secret?, options?)` checks the signature of a [webhook](https://bytesms.com/docs/webhooks) request with your endpoint's `whsec_` secret and returns the parsed event. It rejects timestamps more than 5 minutes off (`{ toleranceSeconds }` changes that) and throws `WebhookVerificationError` when the request is not authentic. No API key is needed.

- `rawBody`: the exact body received, as a `string`, `Buffer`, `Uint8Array` or `ArrayBuffer`. Parsed JSON can't be verified.
- `headers`: a `Headers` object or a plain object such as Node's `req.headers`.
- `secret`: defaults to the `BYTESMS_WEBHOOK_SECRET` environment variable.

Both signature schemes Bytesms sends are supported: `bytesms-signature` and the Svix / Standard Webhooks headers. A standalone `verifyWebhook(rawBody, headers, secret)` is exported too.

**Next.js (App Router)**

```ts
// app/api/webhooks/bytesms/route.ts
import { Bytesms, WebhookVerificationError } from "@bytesms/sdk";

const bytesms = new Bytesms(); // no API key needed to verify

export async function POST(request: Request) {
  const body = await request.text();
  try {
    const event = await bytesms.webhooks.verify(body, request.headers, process.env.BYTESMS_WEBHOOK_SECRET);
    console.log(event.type);
    return new Response("ok");
  } catch (err) {
    if (err instanceof WebhookVerificationError) return new Response(err.message, { status: 400 });
    throw err;
  }
}
```

**Express**

```js
import express from "express";
import { Bytesms, WebhookVerificationError } from "@bytesms/sdk";

const bytesms = new Bytesms();
const app = express();

// express.raw(), not express.json(): the signature covers the exact bytes received
app.post("/webhooks/bytesms", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await bytesms.webhooks.verify(req.body, req.headers, process.env.BYTESMS_WEBHOOK_SECRET);
    if (event.type === "email.bounced") console.log(event.data.email_id);
    res.sendStatus(200);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.status(400).send(err.message);
    throw err;
  }
});
```

## What the SDK covers

| Client property | Methods | API |
| --- | --- | --- |
| `emails` | `send` (alias `create`), `batch`, `list`, `get`, `events`, `update`, `reschedule`, `cancel` | [Emails](https://bytesms.com/docs/emails) |
| `domains` | `create`, `list`, `get`, `verify`, `remove` | [Domains](https://bytesms.com/docs/domains) |
| `apiKeys` | `create`, `list`, `remove` | [API keys](https://bytesms.com/docs/api-keys) |
| `templates` | `create`, `list`, `get`, `update`, `publish`, `duplicate`, `remove` | [Templates](https://bytesms.com/docs/templates) |
| `audiences` | `create`, `list`, `get`, `remove` | [Audiences & contacts](https://bytesms.com/docs/audiences) |
| `contacts` | `create`, `list`, `get`, `update`, `remove` (by contact id or email) | [Audiences & contacts](https://bytesms.com/docs/audiences) |
| `broadcasts` | `create`, `list`, `get`, `update`, `send`, `cancel`, `remove` | [Broadcasts](https://bytesms.com/docs/broadcasts) |
| `webhooks` | `verify` | [Webhooks](https://bytesms.com/docs/webhooks) |

Attachments are not supported by the API yet, so the SDK has no attachment option. More examples (batch, scheduling, templates, broadcasts, Express and Next.js) are in the package README on [npm](https://www.npmjs.com/package/@bytesms/sdk).

### TypeScript types

Request and response types are exported, for example `import type { SendEmailOptions, Email, BytesmsError, WebhookEvent } from "@bytesms/sdk";`.
