# Use the TypeScript SDK

Read, page through and send mail from a Node.js backend.

Source: https://cherami.to/docs/typescript



`@cherami/sdk` gives a Node.js backend typed access to the Cherami HTTP API, with pagination and attachment helpers.

[TypeScript SDK on GitHub](https://github.com/cherami-mail/cherami-typescript) includes the source, runnable examples, and issue tracker.

## Install and connect [#install-and-connect]

The SDK requires Node.js 24 or later. It's an ESM package with TypeScript declarations, for server-side use.

```bash
npm install @cherami/sdk
```

With Bun, run `bun add @cherami/sdk`.

Create a key in [Account → API keys](https://cherami.to/account/api-keys) and supply it privately as `CHERAMI_API_KEY`; we show it only once. It works for every inbox on your account. An agent working for you can get its own instead: choose **Get the message** under **Connect an agent** on your [Account home](https://cherami.to/account) and paste the message to your agent, which exchanges it for a key over HTTP ([how](https://cherami.to/docs/quickstart#ask-your-human-for-approval)).

```ts
import { Cherami } from "@cherami/sdk";

const apiKey = process.env.CHERAMI_API_KEY;
if (!apiKey) throw new Error("Set CHERAMI_API_KEY.");
const client = new Cherami({ apiKey });
const { data } = await client.listInboxes();
console.log(data.inboxes.map(({ id, address }) => ({ id, address })));
```

Each method returns `{ data, status, headers, requestId }`. Inputs keep their HTTP names: resource IDs and query fields go in the parameter object, JSON request fields in `body`.

The examples below continue with this `client`. Replace `inboxId`, message IDs and file paths with your own values.

## Read and paginate [#read-and-paginate]

```ts
const { data: page } = await client.listMessages({ inbox_id: inboxId, limit: 20 });
for (const message of page.messages) {
  const { data: detail } = await client.getMessage({ message_id: message.id });
  if (detail.processing_status === "ready") {
    // Use detail.content.reply_text (the new reply) or detail.content.text, and attachments.
  }
}
```

Only `ready` messages carry `content` ([what to do with the others](https://cherami.to/docs/guides/receiving#wait-for-content-not-just-receipt)). `content.reply_text` holds a reply's new text, or `null` when none could be extracted; an empty string is a real result.

For several pages, use a lazy iterator:

```ts
for await (const message of client.iterate("listMessages", {
  inbox_id: inboxId,
  query: 'invoice "repair workshop"',
  labels_none: ["handled"],
  limit: 50,
}, { maxPages: 5 })) {
  console.log(message.id);
}
```

`iterate` yields items; `pages` yields whole responses, including `next_cursor` to resume later. Pass `maxPages` to stop early; omit it to follow every page. Both also work for sent messages, drafts, labels, Trash and conversations.

Conversation pages from `getThread` come newest first, but each page lists its messages oldest to newest; sort by `timestamp` after collecting several pages. See [search](https://cherami.to/docs/guides/search) and [conversation context](https://cherami.to/docs/guides/conversations).

## Save an intended send before submitting [#save-an-intended-send-before-submitting]

Prepare the send once and save the record, then submit it. If a response is lost, submit the same record again; it won't send twice.

Set `intentPath` to where you'll save this send's record and prepare once:

```ts
import { writeFile, readFile } from "node:fs/promises";
import { prepareSend, restoreSend } from "@cherami/sdk";

const intent = prepareSend("sendMessage", {
  inbox_id: inboxId,
  body: {
    to: [{ address: "recipient@example.com", name: "Alex" }],
    subject: "Review ready",
    text: "The change is ready for review.",
  },
});
await writeFile(intentPath, JSON.stringify(intent));
```

To submit, load the saved record:

```ts
const saved = restoreSend(await readFile(intentPath, "utf8"));
const { data: receipt } = await client.submit(saved);
console.log(receipt.message.id, receipt.message.status, receipt.outcome_persisted);
```

`submit` makes one request and doesn't retry. `rejected` and `unknown` come back as outcomes, not exceptions; the [sending guide](https://cherami.to/docs/guides/sending#inspect-the-outcome) covers what each means. If `outcome_persisted` is false, keep this receipt: later reads may not show its outcome.

`submit` accepts a record for 23 hours and 59 minutes after you prepare it, then throws `SendRecoveryExpiredError`; if the email isn't in `listSentMessages`, prepare it again.

`prepareSend` also covers `replyMessage`, `replyAllMessage` and `forwardMessage`, with their own body fields. Calling `client.sendMessage` or those methods directly sends without a saved record or a generated key; if you do, supply and keep your own `idempotency_key`.

Drafts have no such window: `client.sendDraft({ draft_id: draftId, body: {} })` can be repeated safely. See [draft workflows](https://cherami.to/docs/guides/drafts).

## Handle files and failures [#handle-files-and-failures]

[Attachment examples](https://cherami.to/docs/guides/attachments#download-with-typescript) cover downloads, uploads and sent attachments. Downloads return an unconsumed native `Response` as `data`; consume its `body` as a stream or call `arrayBuffer()` once.

```ts
import { CheramiApiError } from "@cherami/sdk";

try {
  await client.getOutboundQuota();
} catch (error) {
  if (error instanceof CheramiApiError) {
    console.error(error.status, error.code, error.requestId);
  }
  throw error;
}
```

`CheramiApiError` keeps the HTTP status, headers, parsed `body` with any refusal details, `code`, `requestId` and `retryAfter`. Network failures and unreadable responses throw `CheramiTransportError`.

Pass `{ signal, timeoutMs }` as the second method argument, or the first for methods without parameters. The default timeout is 60 seconds, including reading the response body; `0` disables it. The client never follows redirects or retries, and a custom `fetch` you supply must behave the same way.

Named model types and `Params<"operationName">` / `Result<"operationName">` are exported for application code. See the [HTTP reference](https://cherami.to/docs/api) for every field and state.
