TypeScript SDK
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.
Install
npm install @bytesms/sdkSend an email
Create an API key under Dashboard → API Keys (see Authentication). Until you verify a domain, send from [email protected] to your own account email or a @test.bytesms.com test address.
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 <[email protected]>",
to: "[email protected]",
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 reference applies as written.
Keep keys on the server
Client options
new Bytesms(apiKey?, options?). Without an apiKey argument the client reads the BYTESMS_API_KEY environment variable.
Client options
baseUrlstringdefaulthttps://api.bytesms.com/api- API origin including
/api. TheBYTESMS_BASE_URLenvironment variable is used when this is not set. timeoutMsnumberdefault30000- Timeout per attempt, in milliseconds.
maxRetriesnumberdefault2- Extra attempts after the first one for retryable failures (see Retries).
0turns retries off. fetchfunction- Custom
fetchimplementation (tests, proxies). headersobject- Extra headers sent with every request.
Per-call options
idempotencyKeystring- Sent as the
Idempotency-Keyheader onemails.sendandemails.batch, 1 to 256 characters. signalAbortSignal- Cancels the request and any pending retry.
timeoutMsnumber- Overrides the client timeout for this call.
maxRetriesnumber- Overrides the client retry count for this call.
headersobject- Extra headers for this call.
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.
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), 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).
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.
const { data, error } = await bytesms.emails.send(
{ from: "Acme <[email protected]>", 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),5xxresponses,- 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 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 astring,Buffer,Uint8ArrayorArrayBuffer. Parsed JSON can't be verified.headers: aHeadersobject or a plain object such as Node'sreq.headers.secret: defaults to theBYTESMS_WEBHOOK_SECRETenvironment 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.
// 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;
}
}What the SDK covers
| Client property | Methods | API |
|---|---|---|
emails | send (alias create), batch, list, get, events, update, reschedule, cancel | Emails |
domains | create, list, get, verify, remove | Domains |
apiKeys | create, list, remove | API keys |
templates | create, list, get, update, publish, duplicate, remove | Templates |
audiences | create, list, get, remove | Audiences & contacts |
contacts | create, list, get, update, remove (by contact id or email) | Audiences & contacts |
broadcasts | create, list, get, update, send, cancel, remove | Broadcasts |
webhooks | verify | 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.
TypeScript types
Request and response types are exported, for example import type { SendEmailOptions, Email, BytesmsError, WebhookEvent } from "@bytesms/sdk";.
