Charchy Senddocs

Node.js and TypeScript

@charchy/send — the official SDK: typed, zero dependencies, retries that never send twice, a one-line webhook endpoint and end-to-end test helpers. Node 18+, Bun, Deno, Vercel Edge and Cloudflare Workers.

npm install @charchy/send

npm · GitHub (MIT) · Changelog

Zero dependencies, ESM and CommonJS, fully typed. Runs on Node 18+, Bun, Deno (npm:@charchy/send), Vercel (Node and Edge) and Cloudflare Workers. Server code only: the API sends no CORS headers, and the SDK warns if it finds itself in a browser. The key lives in a private field — logging the client shows chy_live_…1a2b, never the key.

Creating the client never needs the key: it is read (the argument, else CHARCHY_SEND_KEY) on each request. A client at the top of a module is safe in next build and in deploys that load code without your secrets; with no key, a call returns missing_api_key and nothing is sent.

Send an email

import { CharchySend } from "@charchy/send"

const send = new CharchySend() // reads CHARCHY_SEND_KEY when a request is made

const { data, error } = await send.emails.send(
  {
    from: { name: "My App", email: "no-reply@myapp.com" },
    to: send.test.address("delivered"), // "delivered@sim.charchy.krd"
    subject: "Hello from Charchy Send",
    html: "<p>It works.</p>",
  },
  { idempotencyKey: "welcome/user-123" }
)

if (error) throw error
console.log(data.id) // "em_…"

Fields are the API's in camelCase (replyTo, scheduledAt, expiresAt, contentType), in and out — except keys inside tags and headers, which stay exactly as you write them. Every field: Send an email.

Addresses are a string ("a@b.com", "Name <a@b.com>"), { name, email } or an array of them; the SDK quotes a name with a comma or quote so it can't split into two recipients, and keeps Kurdish and Arabic names as they are. Input is checked before anything is sent: line breaks in addresses, an expiresAt already past or not after scheduledAt, a malformed idempotency key or an id that isn't em_… come back as validation_error with field.

Results, not exceptions

Every method resolves to { data, error, headers, meta }. error is a CharchySendError with code, message, field, docs, statusCode, requestId (quote it to support), retryAfterSeconds, and for a refused batch items by index. meta is the headers that matter, parsed — requestId, rateLimit ({ limit, remaining, resetSeconds }) and emailsRemaining — and headers keeps them all, lower-cased.

code is an API error code or one of the SDK's own:

CodeMeans
network_errorNo answer: the connection failed, timed out or was aborted
invalid_responseAn answer that isn't the API's JSON — a proxy page, an empty body, or a redirect (never followed)
react_render_errorreact given, but @react-email/render is missing or the render threw
wait_timeoutemails.waitFor ran out of time
wait_unexpected_statusemails.waitFor saw the email end canceled, expired, failed or unknown
import { unwrap } from "@charchy/send"

// Prefer exceptions? unwrap returns data or throws the CharchySendError.
const { id } = await send.emails.send({ from, to, subject: "Receipt", text: "Thanks!" }).then(unwrap)

Retries and idempotency

Up to maxRetries extra attempts (default 2), jittered backoff:

AnswerRetried?
429, 409 idempotency_in_flightAfter Retry-After — unless it is over 60 seconds (a daily cap comes back at once)
Network error, timeout, 5xxSends, reads, reschedule and cancel. Not image uploads
402 insufficient_balance, every other 4xx, a redirectNever

A retry never sends twice: emails.send and emails.batch without an idempotencyKey get a random one on the first attempt, reused by every retry of that call. It covers the SDK's own retries only — a second call is a new email. Pass your own key, built from the event behind the email, and your job retries are safe too (Idempotency):

await send.emails.send({ from, to, subject: "Order confirmed", html }, { idempotencyKey: `order-confirmation/${order.id}` })

Every method

// One email: addresses as strings or { name, email }; Date, ISO or "10m"/"2h"/"1d" for times.
await send.emails.send({ from, to, cc, bcc, replyTo, subject, html, text, tags, headers, scheduledAt: "1d", expiresAt: "26h", attachments })

// Up to 100 emails, no attachments, all accepted or none.
await send.emails.batch(users.map((user) => ({ from, to: user.email, subject, html })), { idempotencyKey: "weekly-receipts/2026-W47" })

await send.emails.get("em_…")                                  // status, recipients, events
await send.emails.waitFor("em_…", { until: ["delivered"] })   // reads until then: for tests and CI
await send.emails.list({ limit: 50, status: "bounced", tag: "type:order", to: "a@b.com" })
for await (const email of send.emails.listAll({ status: "bounced" })) {} // follows next_cursor; throws on a failed page
await send.emails.update("em_…", { scheduledAt: "2026-11-20T08:00:00+03:00" })
await send.emails.cancel("em_…")

await send.images.upload(await readFile("logo.png"), { filename: "logo.png" }) // → { id, url, contentType, size }
await send.usage.get()                                         // plan, credits, daily { cap, surgeCap, used, resetsAt }, test
  • Durations ("30s", "10m", "2h", "1d") become an ISO time with your server's clock; the API itself takes ISO 8601 only.
  • Attachments take Buffer, Uint8Array, ArrayBuffer, Blob or a base64 string; contentType is inferred for common extensions (pdf, png, jpg, gif, webp, txt, csv, ics, html, json, zip).
  • React Email: react: <WelcomeEmail /> is rendered to html with @react-email/render (npm install @react-email/render, an optional peer).
  • Every method takes { signal } to abort it and its retries.

Test end to end

console.log(send.mode) // "test" (chy_test_ key), "live", or null while there is no valid key

const { id } = await send.emails
  .send({ from, to: send.test.address("bounced", "signup-42"), subject: "Test", text: "t" })
  .then(unwrap)
const { data, error } = await send.emails.waitFor(id, { until: ["bounced"], timeoutMs: 30_000 })

send.test.address(outcome, label?) builds a magic address — "delivered", "bounced", "complained", "suppressed" or "delayed", with an optional label of letters, digits, _ and -. waitFor reads the email until it reaches a status in until (default: any status it ends in), every intervalMs (1 s), for up to timeoutMs (60 s). It returns wait_timeout when time runs out and wait_unexpected_status at once when the email ends canceled, expired, failed or unknown instead.

Webhook endpoint in one line

webhookHandler (also send.webhooks.handler) is a complete endpoint — a standard (request: Request) => Promise<Response> for the Next.js App Router, Cloudflare Workers, Bun, Deno and Hono. One typed function per event you care about:

// app/api/webhooks/charchy/route.ts
import { webhookHandler } from "@charchy/send"

export const POST = webhookHandler({
  "email.bounced": (event) => markBounced(event.data.recipient, event.data.bounce.type),
  "email.complained": (event) => markComplained(event.data.recipient),
  "balance.low": (event) => alertOps(`${event.data.emailsLeft} emails left`),
})
AnswerWhen
204Verified, and its handler finished — or there is none for that type
400The request fails verification (no detail is given to the sender)
405Not a POST
500A handler threw, or the secret is missing — Charchy Send retries the event

The secret defaults to CHARCHY_WEBHOOK_SECRET; pass { secret, onError } to change it or log refusals. Handlers run before the answer, which must come within 5 seconds: keep them short or hand the work to a queue.

Verify webhooks yourself

verifyWebhook (also send.webhooks.verify) checks the Standard Webhooks signature against the raw body, refuses timestamps more than 5 minutes off, accepts either secret during a rotation, and returns a typed event. It throws WebhookVerificationError when the request must be refused — including a body that was already parsed (express.json()): pass the raw body. The secret defaults to CHARCHY_WEBHOOK_SECRET; it uses Web Crypto, so it runs on the edge too.

// app/api/webhooks/charchy/route.ts
import { after } from "next/server"
import { verifyWebhook, WebhookVerificationError } from "@charchy/send"

export async function POST(request: Request) {
  try {
    const event = await verifyWebhook({ payload: await request.text(), headers: request.headers })
    after(() => handleCharchyEvent(event)) // answer first, work later
    return new Response(null, { status: 204 })
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new Response(error.message, { status: 400 })
    throw error
  }
}

The event is camelCased and discriminated by type, so data narrows:

switch (event.type) {
  case "email.bounced":
    await markBounced(event.data.recipient, event.data.bounce.type)
    break
  case "account.paused":
    await alertOps(`${event.data.code}: ${event.data.reason}`)
    break
}

Dedupe by event.id and order by event.createdAt (Webhooks).

Options

const send = new CharchySend(process.env.CHARCHY_SEND_KEY, {
  baseUrl: "https://api.charchy.krd", // the default; https only (http just for localhost)
  maxRetries: 2,                      // 0–10; 0 turns retries and the automatic key off
  timeoutMs: 30_000,                  // per attempt, at most 600 000
  fetch: customFetch,                 // a proxy-aware fetch, or a test double
  userAgent: "my-app/2.3",            // appended to charchy-send-node/<version>
})

The key defaults to CHARCHY_SEND_KEY and must be chy_live_ or chy_test_ plus 64 hex characters, checked on each request: missing is missing_api_key, anything else invalid_api_key — local errors, nothing sent, never echoing what you passed. A bad option is a code error and throws at once. Redirects are never followed. With a test key nothing is sent or charged and webhooks still fire.

Help

Bugs and feature requests: GitHub issues. Questions about your account: support@charchy.krd — include error.requestId. Security reports: SECURITY.md.

On this page