---
title: Node.js SDK
description: Use BillionSend from Node.js and TypeScript with the @billionsend/node package.
---

The `@billionsend/node` package is the BillionSend client for Node.js and TypeScript. It covers every operation of the [API reference](/docs/api-reference): sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. Its types come from the API's OpenAPI document. The source is [billionsend/billionsend-node](https://github.com/billionsend/billionsend-node) on GitHub.

## Install

Needs Node 18 or newer. The package has no dependencies and ships both ES modules and CommonJS.

```sh
npm install @billionsend/node
```

## Send an email

```ts
import { BillionSend } from "@billionsend/node";

const bs = new BillionSend(); // reads BILLIONSEND_API_KEY

const { data, error } = await bs.emails.send(
  {
    from: "Acme <hello@acme.dev>",
    to: ["ana@example.com"],
    subject: "Welcome to Acme",
    html: "<p>Glad you are here.</p>",
  },
  { idempotencyKey: "welcome/ana" },
);

if (error) console.error(error.statusCode, error.name, error.message, error.requestId);
else console.log(data.id);
```

`new BillionSend("bs_...")` takes the key directly; `new BillionSend({ apiKey, baseUrl, timeoutMs, maxRetries, fetch })` sets the rest. `BILLIONSEND_BASE_URL` overrides the API URL.

## Idempotency and retries

The sending methods (`emails.send`, `emails.batch`, replies and forwards, `inboxes.send`, `inboxes.drafts.send`) always send an `Idempotency-Key`. Without your own `idempotencyKey`, each call gets a new random key that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe.

Failures worth retrying are retried twice by default (`maxRetries`): 429, 5xx, timeouts, network errors, and the `409 concurrent_idempotent_requests` answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: reads, `PUT` and `DELETE`, and the sending methods. The client waits as `retry-after` asks, up to a minute, and otherwise backs off exponentially.

## Errors

Methods never throw. Each one resolves to `{ data, error, headers }` with exactly one of `data` and `error` set. `error` is a `BillionSendError` of a class for its kind: `ValidationError` (400, 422), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429, with `retryAfter` in seconds), `APIError` (5xx), `APIConnectionError` and `APITimeoutError` (no answer). Each carries `statusCode`, `name` (the API's error name), `message` and `requestId`, the `x-request-id` of the answer, which is the request's id on the dashboard's Logs page.

```ts
import { NotFoundError } from "@billionsend/node";

const { data, error } = await bs.emails.get(id);
if (error instanceof NotFoundError) return null;
if (error) throw error;
```

`listAll` and the event streams throw the same errors, since they cannot return one per item.

## An agent's inbox

Wait for new mail on the [event stream](/docs/inboxes), read it, and reply in its thread:

```ts
const inbox = "support@acme.dev";
const opened = await bs.inboxes.events.streamInbox(inbox, { types: "inbox.email.received" });
if (opened.error) throw opened.error;

for await (const item of opened.data) {
  if (item.event === "stream.gap") continue; // events may be missing: read the threads again
  const { thread_id, email_id } = item.data.data;
  if (!thread_id || !email_id) continue;

  const email = await bs.inboxes.threads.emails.get(inbox, thread_id, email_id);
  if (email.error) throw email.error;

  await bs.inboxes.threads.emails.reply(
    inbox,
    thread_id,
    email_id,
    { text: await draftAnswer(email.data.text) },
    { idempotencyKey: `reply/${email_id}` },
  );
}
```

The stream reconnects with `Last-Event-ID` when the connection drops and replays what it missed, so no event is lost; keep `opened.data.lastEventId` to resume in a later run with `{ lastEventId }`. A `stream.gap` comes once when the stream resumes from more than 24 hours back. One inbox's stream ends after that inbox is deleted or expires; `bs.inboxes.events.stream()` follows every inbox of the team.

## Verify webhooks

`verifyWebhook` checks a [webhook](/docs/concepts/webhooks) delivery's signature and timestamp with the endpoint's `whsec_` secret and returns the parsed event. Pass the body exactly as it arrived:

```ts
import { verifyWebhook, WebhookVerificationError } from "@billionsend/node";

try {
  const event = await verifyWebhook(await request.text(), request.headers, process.env.BILLIONSEND_WEBHOOK_SECRET);
  if (event.type === "email.bounced") {
    // ...
  }
} catch (error) {
  if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
  throw error;
}
```

With Express, read the body with `express.raw({ type: "application/json" })` and pass `req.body` and `req.headers`. A delivery older than five minutes is refused (`tolerance` changes it), and during a secret rotation either secret verifies.

## Agent sign-up

```ts
const signup = await new BillionSend().agent.signup({
  human_email: "owner@acme.dev",
  name: "Support agent",
});
if (signup.data) console.log(signup.data.inbox.email_address);
```

The call needs no API key; the answer carries the new key and the inbox. See [Agent sign-up](/docs/agent-signup) for what an unclaimed account may do.
