# JavaScript SDK

> The official JavaScript and TypeScript SDK: sending, contacts, broadcasts, webhooks and more.

Source: https://sndr.sh/docs/quickstart

## Install

npm:

```bash
npm install @rkiza/sndr
```

pnpm:

```bash
pnpm add @rkiza/sndr
```

bun:

```bash
bun add @rkiza/sndr
```

Version **0.3.0** supports Node.js 18+ and runtimes with Node-compatible `node:crypto`, `Buffer` and `fetch`. Cloudflare Workers requires `nodejs_compat` for the SDK import. In Next.js, use the Node.js runtime; for an edge runtime without Node compatibility, use the HTTP API with `fetch`. Keep your API key on the server.

## Send an email

send.ts:

```js
import { Sndr } from '@rkiza/sndr';

const apiKey = process.env.SNDR_API_KEY;
if (!apiKey) throw new Error('Set SNDR_API_KEY');
const sndr = new Sndr(apiKey);

const email = await sndr.emails.send({
  from: 'Acme <hello@mail.acme.com>',
  to: 'customer@example.com',
  subject: 'Hello from SNDR',
  html: '<p>It works.</p>',
});

console.log(email.id); // eml_...
```

`to`, `cc` and `bcc` accept one address or an array. The SDK adds an `Idempotency-Key` to each send and reuses it across its retries. Pass your own stable key to deduplicate separate calls for the same operation; a new SDK call otherwise gets a new key.

## Options

- `apiKey` (string, required): Your API key. Pass it as the only argument, or inside an options object.
- `baseUrl` (string): API host. Defaults to `https://api.sndr.sh`.
- `retries` (object | false): Reads and email sends retry network failures and HTTP 429/500/502/503/504. Other writes are attempted once. Defaults: `maxAttempts: 3`, `baseDelayMs: 250`, `maxDelayMs: 5000`; partial overrides are supported. `Retry-After` is respected even above the backoff cap. Pass `false` to disable retries.

## Handle errors

```js
import { Sndr, SndrError } from '@rkiza/sndr';

try {
  await sndr.emails.send({ from: 'hello@mail.acme.com', to: 'customer@example.com', subject: 'Hello', text: 'Welcome' });
} catch (err) {
  if (err instanceof SndrError) {
    console.error(err.code, err.status, err.requestId, err.fields);
  }
}
```

`code` matches the [error codes](https://sndr.sh/docs/errors). `fields` and `field` expose validation details. `currentLimit`, `currentUsage`, `upgradeRequired`, `resource`, `docsUrl` and `retryAfterSeconds` preserve quota and retry context; `details` contains the original API error and `response` the complete error body. Include `requestId` when contacting support. Cancellation throws `SndrError` with code `aborted`; an SDK timeout uses `timeout`.

## Other resources

Every public API endpoint has a **Node.js SDK** example in the [API reference](https://sndr.sh/docs/api-reference). The SDK uses API-key authentication; the Partner API uses OAuth and its own HTTP examples.

| Resource | Methods |
| --- | --- |
| `sndr.emails` | `send`, `list`, `get` |
| `sndr.domains` | `list`, `create`, `verify`, `delete` |
| `sndr.templates` | `list`, `get`, `create`, `update`, `delete` |
| `sndr.contacts` | `list`, `get`, `create`, `bulk`, `update`, `delete` |
| `sndr.contactGroups` | `list`, `get`, `create`, `update`, `delete`, `members`, `addMembers`, `removeMembers` |
| `sndr.broadcasts` | `list`, `get`, `create`, `update`, `delete`, `send`, `recipients` |
| `sndr.suppressions` | `list`, `create`, `delete` |
| `sndr.webhooks` | `list`, `create`, `delete`; `signingKeys.list`, `.stage`, `.promote`, `.retire` |
| `sndr.apiKeys` | `list` only. Create and revoke in the dashboard. |
| `sndr.analytics` | `summary` with `1d`, `7d`, `30d` (default) or `90d` |

## Request options and pagination

Every method accepts request options. For list methods, combine these with filters in the same object. The default 30-second timeout covers all attempts and backoff; `timeoutMs: 0` disables it. Supplying `signal` makes the caller responsible for cancellation and replaces the SDK timeout. `idempotencyKey` is honored only by `emails.send` (24-hour retention); never reuse one key for different email bodies.

```ts
let cursor: string | undefined;
do {
  const page = await sndr.contacts.list({ limit: 100, cursor, status: 'subscribed', timeoutMs: 5000 });
  for (const contact of page.data) console.log(contact.email);
  cursor = page.has_more ? page.next_cursor : undefined;
} while (cursor);
```

`emails.list`, `contacts.list` and `broadcasts.list` return cursor pages: `data`, `has_more`, `next_cursor`, `count`, `limit`. `contactGroups.members` and `broadcasts.recipients` use `limit`/`offset` and return `data`/`total`. Other lists return `data`; `webhooks.list` also includes page metadata. Contacts can be filtered by `status`, `group_id` and `q`.

## Templates and attachments

```js
const template = await sndr.templates.create({
  name: 'Receipt', subject: 'Thanks {{ customer.name }}', text: 'Your receipt is attached.',
});
await sndr.emails.send({
  from: 'Acme <hello@mail.acme.com>', to: 'customer@example.com',
  template_id: template.id, variables: { customer: { name: 'Sam' } },
  attachments: [{ filename: 'receipt.txt', content: Buffer.from('Receipt #123').toString('base64'), content_type: 'text/plain' }],
}, { idempotencyKey: 'receipt-123' });
```

A template can supply the subject and body. Without a template, provide `subject` and `html` or `text`. Up to 10 attachments, 10 MiB total decoded content, 16 MiB total JSON request. Content must be base64, not a URL or data URI. Never place untrusted values directly in HTML.

## Contacts and broadcasts

```js
const group = await sndr.contactGroups.create({ name: 'Newsletter' });
const imported = await sndr.contacts.bulk({
  contacts: [{ email: 'customer@example.com', first_name: 'Sam' }],
  group_ids: [group.id], source: 'api',
});
console.log(imported.inserted, imported.updated, imported.skipped, imported.errors);
const draft = await sndr.broadcasts.create({
  name: 'Product news', group_id: group.id, from_email: 'Acme <hello@mail.acme.com>',
  subject: 'Product news', text: 'Hello {{ first_name }}',
});
// Sends to subscribed members. Call only when you are ready to release the campaign.
const queued = await sndr.broadcasts.send(draft.id);
console.log(queued.recipients);
```

Bulk requests accept at most 500 contacts. Existing opt-outs stay opted out unless explicitly changed. Inspect `errors` as well as the inserted/updated/skipped counts. Broadcasts are editable only while draft; an empty subscribed audience is rejected and remains draft. Mutations other than email sends are never automatically retried.

## Webhooks and analytics

`webhooks.create` returns the full signing `secret` once. `webhooks.signingKeys.stage(webhookId)` returns the staged secret; deploy that secret in your verifier before calling `.promote(webhookId, keyId)`. Use `.retire` to roll back an unpromoted secondary. `verifyWebhookSignature` accepts primary and staged signatures with a five-minute freshness check — see [Webhooks](https://sndr.sh/docs/webhooks).

```js
const stats = await sndr.analytics.summary('30d');
console.log(stats.sent, stats.delivered, stats.bounced, stats.failed, stats.complained);
console.log(stats.inbox_rate, stats.as_of);
```

Analytics no longer returns `opened`, `clicked` or `series`. `inbox_rate` is the delivered / sent ratio, between 0 and 1, not a measurement of inbox placement. Upgrade from 0.2.0 with `npm install @rkiza/sndr@latest`; update code reading the removed analytics fields. CommonJS uses `const { Sndr } = require('@rkiza/sndr')`.
