Node.js SDK

The sendfern package is the official client for Node.js and TypeScript. It covers every resource in the API, retries safely, and verifies webhook signatures.

Requirements

  • Node.js 18 or later. The SDK uses the built-in fetch and node:crypto.
  • No dependencies.
  • TypeScript types are included; there is no separate @types package.
  • The package is an ES module. Use import; from CommonJS, load it with await import("sendfern").

Install

Terminal
npm install sendfern
# or
pnpm add sendfern
# or
yarn add sendfern

Configure the client

Create one client and reuse it. The first argument is your API key. Leave it out and the client reads SENDFERN_API_KEY; with neither, the constructor throws.

sendfern.ts
import { Sendfern } from "sendfern";

// Reads SENDFERN_API_KEY when you leave the key out.
const sendfern = new Sendfern();

// Or pass everything yourself.
const custom = new Sendfern("sk_live_...", {
  baseUrl: "https://api.sendfern.com",
  timeoutMs: 10_000,
  maxRetries: 3,
});

Options

baseUrlstring
The API address. Defaults to SENDFERN_BASE_URL, then https://api.sendfern.com. A trailing slash is removed.
timeoutMsnumber
Time limit for each attempt, in milliseconds. Default 30000.
maxRetriesnumber
Retries after the first attempt. Default 2, so a call makes at most 3 attempts. See Retries.
fetchtypeof fetch
A replacement for the global fetch, for example to log requests or to use a proxy.
logging.ts
import { Sendfern } from "sendfern";

const sendfern = new Sendfern(process.env.SENDFERN_API_KEY, {
  fetch: async (url, init) => {
    console.log(init?.method, url);
    return fetch(url, init);
  },
});

A test key (sk_test_) accepts the same calls but sends nothing. Domains, templates, audiences, contacts, webhooks and suppressions are shared between modes, and a test key can read them but not change them: creating, updating or deleting one with a test key fails with 403 permission_denied. A send-only key can call only emails.send and emails.batch. See Authentication.

Send an email

send.ts
import { Sendfern } from "sendfern";

const sendfern = new Sendfern(process.env.SENDFERN_API_KEY);

const email = await sendfern.emails.send({
  from: "Acme <onboarding@acme.com>",
  to: "user@example.com",
  subject: "Welcome to Acme",
  html: "<p>Thanks for signing up.</p>",
  text: "Thanks for signing up.",
});

console.log(email.id); // em_...

You get the email object back at once, with status queued; sending happens in the background. The From address must be on a verified domain when you use a live key. Every field is described in Send an email.

Resources

Each resource is a property of the client. Methods return the parsed JSON response, and a remove or revoke returns null. Request bodies use the API's field names (template_id, scheduled_at), and list methods take the API's query parameters as an object. For every field of every object, see the API reference.

Emails

emails.ts
// Send up to 100 emails in one request. Nothing is queued if any item is invalid.
const { data } = await sendfern.emails.batch([
  { from: "Acme <hello@acme.com>", to: "a@example.com", subject: "Hi", text: "Hello" },
  { from: "Acme <hello@acme.com>", to: "b@example.com", subject: "Hi", text: "Hello" },
]);

// Schedule one for later, then change your mind.
const later = await sendfern.emails.send({
  from: "Acme <hello@acme.com>",
  to: "user@example.com",
  subject: "Your trial ends tomorrow",
  text: "Upgrade any time.",
  scheduled_at: "2026-12-01T09:00:00Z",
});
await sendfern.emails.cancel(later.id);

// Read one with its body and timeline, list with filters, send a copy.
const email = await sendfern.emails.get("em_VNqV5JEIqYYeYbZRhbPrJ6");
const bounced = await sendfern.emails.list({ status: "bounced", limit: 50 });
const copy = await sendfern.emails.resend("em_VNqV5JEIqYYeYbZRhbPrJ6");
MethodWhat it does
emails.send(email, opts?)Send one email. opts takes idempotencyKey.
emails.batch(emails, opts?)Send 1 to 100 emails in one request. Returns { data: Email[] }.
emails.get(id)One email with html, text, body_cleared_at and its events.
emails.list(params?)Filters: status, to, tag (name:value), broadcast_id, created_after, created_before, q (subject contains), limit.
emails.cancel(id)Cancel a scheduled email.
emails.resend(id)Send a new copy now, with a new id. Not for broadcast emails.

Domains

domains.ts
const domain = await sendfern.domains.create("acme.com");
for (const r of domain.records) console.log(r.type, r.name, r.value);

// After you add the DNS records:
const checked = await sendfern.domains.verify(domain.id);
console.log(checked.status); // "pending", "verified" or "failed"

await sendfern.domains.update(domain.id, { track_opens: false, tracking_domain: "links.acme.com" });
MethodWhat it does
domains.create(name)Add a domain. The response lists the DNS records to create.
domains.list(params?)All domains.
domains.get(id)One domain.
domains.verify(id)Check the DNS records now and return the updated domain.
domains.update(id, tracking)Change track_opens, track_clicks or tracking_domain.
domains.remove(id)Delete the domain.

See Domains and DNS and Open and click tracking.

Templates

templates.ts
const template = await sendfern.templates.create({
  name: "Welcome",
  subject: "Welcome, {{ first_name }}",
  html: "<p>Hi {{ first_name }}, <a href=\"{{ action_url }}\">finish setting up</a>.</p>",
});

// Preview with sample values. Missing variables are left as written.
const preview = await sendfern.templates.render(template.id as string, { first_name: "Jane" });

// Send with it: no subject, html or text.
await sendfern.emails.send({
  from: "Acme <hello@acme.com>",
  to: "user@example.com",
  template_id: "tpl_...",
  variables: { first_name: "Jane", action_url: "https://acme.com/setup" },
});
MethodWhat it does
templates.create(template)name, subject, and html or text. The response lists its variables.
templates.list(params?)All templates.
templates.get(id)One template.
templates.update(id, template)Change any of name, subject, html, text.
templates.remove(id)Delete it. Emails already created from it don't change.
templates.render(id, variables?)Returns { subject, html, text } for a preview.

When you send with template_id, every variable the template uses must be in variables, or the send fails with 400. See Templates.

Audiences and contacts

audiences.ts
const audience = await sendfern.audiences.create("Newsletter");

// Upsert by email: creates the contact or updates the one with that address.
await sendfern.contacts.upsert(audience.id as string, {
  email: "user@example.com",
  first_name: "Jane",
});

const unsubscribed = await sendfern.contacts.list(audience.id as string, { status: "unsubscribed" });
MethodWhat it does
audiences.create(name)Create an audience.
audiences.list(params?)All audiences, with contact_count and subscribed_count.
audiences.get(id)One audience.
audiences.update(id, audience)Rename it (name).
audiences.remove(id)Delete it and its contacts. Fails if a broadcast uses it.
contacts.upsert(audienceId, contact)Create or update by email, with first_name, last_name, unsubscribed.
contacts.list(audienceId, params?)Filters: email (contains), status (subscribed or unsubscribed), limit.
contacts.get(id)One contact.
contacts.update(id, contact)Change names or unsubscribed.
contacts.remove(id)Delete the contact.

The SDK has no method for CSV import; use the dashboard or the API. See Audiences and contacts.

Broadcasts

broadcasts.ts
const broadcast = await sendfern.broadcasts.create({
  name: "December update",
  audience_id: "aud_...",
  from: "Acme <news@acme.com>",
  subject: "What's coming in December",
  html: "<p>Hi {{first_name}}, here is a first look.</p><p><a href=\"{{unsubscribe_url}}\">Unsubscribe</a></p>",
  text: "Hi {{first_name}}, here is a first look.\n\nUnsubscribe: {{unsubscribe_url}}",
});
const id = broadcast.id as string;

const { checks, recipient_count } = (await sendfern.broadcasts.checks(id)) as {
  checks: { id: string; ok: boolean; level: string; message?: string }[];
  recipient_count: number;
};

await sendfern.broadcasts.test(id, "me@acme.com");

// Send now, or pass scheduledAt (a Date or an ISO string, up to 30 days ahead).
await sendfern.broadcasts.send(id, { scheduledAt: new Date("2026-12-01T09:00:00Z") });
await sendfern.broadcasts.cancel(id); // back to draft
MethodWhat it does
broadcasts.create(broadcast)name, audience_id, from, subject, html and text (or blocks), optional reply_to and preview_text.
broadcasts.list(params?)Filters: status, audience_id, q, limit.
broadcasts.get(id)One broadcast, with stats.
broadcasts.update(id, broadcast)Edit a draft.
broadcasts.remove(id)Delete it.
broadcasts.checks(id)The before-you-send checks and the recipient count.
broadcasts.test(id, to)Send one test copy to an address.
broadcasts.send(id, { scheduledAt }?)Send now, or schedule up to 30 days ahead.
broadcasts.cancel(id)Unschedule. The broadcast goes back to draft.

Sending is refused while an error-level check fails, for example a missing plain-text version. See Broadcasts.

Suppressions

suppressions.ts
await sendfern.suppressions.create("user@example.com");

const { data } = await sendfern.suppressions.list({ email: "user@example.com" });
if (data[0]) await sendfern.suppressions.remove(data[0].id as string);
MethodWhat it does
suppressions.create(email)Stop sending to an address.
suppressions.list(params?)Filter with email.
suppressions.remove(id)Allow the address again.

Webhooks

webhooks.ts
const endpoint = await sendfern.webhooks.create({
  url: "https://acme.com/webhooks/sendfern",
  events: ["email.delivered", "email.bounced", "email.complained"],
});
console.log(endpoint.secret); // whsec_..., returned only now

await sendfern.webhooks.test(endpoint.id as string);
const { data: deliveries } = await sendfern.webhooks.deliveries(endpoint.id as string, { limit: 10 });
await sendfern.webhooks.retry(endpoint.id as string, deliveries[0].id as string);
MethodWhat it does
webhooks.create({ url, events?, enabled? })Add an endpoint. No events means all. The secret is in this response only.
webhooks.list(params?)All endpoints.
webhooks.get(id)One endpoint.
webhooks.update(id, webhook)Change url, events or enabled.
webhooks.remove(id)Delete the endpoint.
webhooks.deliveries(id, params?)The delivery log, newest first.
webhooks.test(id)Send a sample email.delivered event now.
webhooks.retry(id, deliveryId)Try a failed delivery once more.

API keys

keys.ts
const { data: keys } = await sendfern.apiKeys.list();
await sendfern.apiKeys.revoke("key_...");
MethodWhat it does
apiKeys.list(params?)Your keys, without their secrets.
apiKeys.revoke(id)Revoke a key. It stops working at once. A key cannot revoke itself.

You create keys in the dashboard; the API does not create keys with an API key.

Stats and usage

stats.ts
const stats = await sendfern.stats.get({ from: "2026-11-01", to: "2026-11-25", tag: "type:welcome" });

const usage = await sendfern.usage.get();
console.log(`${usage.used} of ${usage.quota ?? "unlimited"} this month`);
MethodWhat it does
stats.get(params?)Totals and a daily series. Params: from, to (UTC dates, at most 90 days), interval, broadcast_id, tag.
usage.get()Live emails this calendar month: period_start, period_end, used, quota.

Other endpoints

sendfern.request(method, path, body?, opts?) calls any endpoint with the same authentication, retries and errors.

request.ts
// Any endpoint, with the same auth, retries and errors.
const page = await sendfern.request("GET", "/v1/emails?status=delivered&limit=5");

Idempotency keys

Pass idempotencyKey to emails.send or emails.batch. If the same key arrives again with the same body within 24 hours, the API returns the first response instead of sending again. The same key with a different body is a 409. Use something that identifies the action, like an order id.

receipt.ts
await sendfern.emails.send(
  {
    from: "Acme <hello@acme.com>",
    to: "user@example.com",
    subject: "Your receipt",
    html: "<p>Thanks for your order.</p>",
  },
  { idempotencyKey: `receipt-${order.id}` },
);

A key also lets the SDK retry a send after a server or network error. See Idempotency.

Pagination

List methods return one page: { data, has_more, next }, newest first, 20 items by default and up to 100 with limit. paginate walks every page for you and keeps your filters.

paginate.ts
// Every bounced email, page after page.
for await (const email of sendfern.paginate((p) => sendfern.emails.list(p), { status: "bounced", limit: 100 })) {
  console.log(email.to);
}

// Lists that take an id first: wrap the call.
for await (const contact of sendfern.paginate((p) => sendfern.contacts.list("aud_...", p))) {
  console.log(contact.email);
}

Errors

A failed call throws SendfernError. It carries the API's error object and the HTTP status.

statusnumber
The HTTP status. 0 when Sendfern could not be reached (network error or timeout).
typestring
For example invalid_request_error or rate_limit_error.
codestring
For example invalid_parameter, domain_not_verified, or network_error when status is 0.
paramstring | null
The request field the error is about, when there is one.
messagestring
A sentence you can log or show to a developer.
errors.ts
import { Sendfern, SendfernError } from "sendfern";

try {
  await sendfern.emails.send({ from: "Acme <hello@acme.com>", to: "not-an-address", subject: "Hi", text: "Hello" });
} catch (err) {
  if (err instanceof SendfernError) {
    console.error(err.status, err.type, err.code, err.param, err.message);
    // 400 invalid_request_error invalid_parameter to 'not-an-address' is not a valid email address.
  } else {
    throw err;
  }
}

The full list of types and codes is in Errors.

Retries

The SDK retries a failed attempt up to maxRetries times (default 2):

  • 429 Too Many Requests is retried for every method, because the request was not processed.
  • 5xx responses, network errors and timeouts are retried only when a repeat is safe: for every method except POST (GET, PATCH and DELETE), and for a POST that has an idempotencyKey.

Before a retry the SDK waits for the number of seconds in the Retry-After header when the response has one. Otherwise it backs off: about 0.5 s, then 1 s, doubling up to 8 s, with random jitter. When the retries run out, the last error is thrown.

Verify webhooks

Every webhook request has an X-Sendfern-Signature header. verifyWebhook(secret, header, rawBody) returns true when the signature matches your endpoint's secret (whsec_...) and the timestamp is within 5 minutes. Change the window with { toleranceSeconds } as a fourth argument.

Pass the body exactly as it arrived. A body that was parsed and serialized again will not match, so read it raw before any JSON middleware runs.

server.ts
import express from "express";
import { verifyWebhook } from "sendfern";

const app = express();

// express.raw keeps the body as bytes: the signature is over the exact body.
app.post("/webhooks/sendfern", express.raw({ type: "application/json" }), (req, res) => {
  const rawBody = req.body.toString("utf8");
  const ok = verifyWebhook(process.env.SENDFERN_WEBHOOK_SECRET!, req.get("X-Sendfern-Signature"), rawBody);
  if (!ok) return res.status(400).end();

  const event = JSON.parse(rawBody);
  if (event.type === "email.bounced") {
    // ...
  }
  res.status(200).end();
});

Answer with a 2xx quickly and do slow work afterwards. Events can arrive more than once, so use the event id to skip duplicates. See Webhooks.

TypeScript

The package ships its own declarations. Besides the client, it exports these types:

TypeWhat it describes
SendEmailThe body of emails.send and each item of emails.batch.
EmailThe email object.
EmailDetailEmail plus html, text, body_cleared_at and events (from emails.get).
EmailStatusThe union of email statuses, from queued to suppressed.
DomainThe domain object, with its records.
Attachmentfilename, base64 content, optional content_type.
Address, AddressesOne address string, or one or many.
List<T>A page: data, has_more, next.
SendfernOptionsThe constructor options.
RequestOptionsPer-call options: idempotencyKey.
JsonRecord<string, unknown>, returned where no dedicated type exists yet.
SendfernErrorThe error class, with type, code, param and status.
typed.ts
import { Sendfern, type Email, type SendEmail } from "sendfern";

const sendfern = new Sendfern();

function welcome(to: string): SendEmail {
  return { from: "Acme <hello@acme.com>", to, subject: "Welcome", text: "Thanks for signing up." };
}

const email: Email = await sendfern.emails.send(welcome("user@example.com"));

// Many resources return Json (Record<string, unknown>). Describe the fields you use.
type Audience = { id: string; name: string; contact_count: number; subscribed_count: number };
const audience = (await sendfern.audiences.get("aud_...")) as Audience;

Versioning

The SDK follows semantic versioning. While it is at 0.x, a minor release (0.1 to 0.2) may contain breaking changes, so pin the minor version, for example "sendfern": "~0.1.0". The package is sendfern on npm. The Python SDK has a matching API.