Charchy Senddocs

Hono

A Hono backend on Cloudflare Workers, Bun or Node.js — one client for every route, sending from routes and after the response, a webhook endpoint, and Better Auth sign-in codes for a frontend on another origin.

@charchy/send/hono adds a middleware that puts a client on c.var and a webhook handler. Both read the secrets where each runtime keeps them, so the same app runs on Workers, Bun and Node.js.

1. Install

npm install @charchy/send hono

@charchy/send 0.2 or later, Hono 4. On Node.js, add @hono/node-server.

2. Secrets on each runtime

The middleware reads CHARCHY_SEND_KEY, and the webhook handler CHARCHY_WEBHOOK_SECRET, from the first place that has it: the binding on c.env, then process.env, then Deno.env.

RuntimeRead fromLocalProduction
Cloudflare Workersc.env binding.dev.varsnpx wrangler secret put CHARCHY_SEND_KEY
Bunprocess.env.env (Bun loads it)The host's environment
Node.js (@hono/node-server)process.env--env-file=.envThe host's environment
Deno, Supabase Edge Functions, Netlify Edgeprocess.env / Deno.env (needs --allow-env)deno run --env-file --allow-envThe platform's secrets
Vercel, AWS Lambdaprocess.env.envProject / function environment variables
Lambda@Edge, Fastly ComputeNo environment variables—Pass apiKey (below)

On Workers, everything this guide uses:

wrangler.jsonc
{
  "name": "my-app-api",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-01",
  "d1_databases": [{ "binding": "DB", "database_name": "my-app", "database_id": "…" }],
  "vars": { "FRONTEND_ORIGIN": "https://app.myapp.com", "BETTER_AUTH_URL": "https://api.myapp.com" }
}
.dev.vars
CHARCHY_SEND_KEY=chy_test_…
CHARCHY_WEBHOOK_SECRET=whsec_…
BETTER_AUTH_SECRET=…
npx wrangler secret put CHARCHY_SEND_KEY
npx wrangler secret put CHARCHY_WEBHOOK_SECRET
npx wrangler secret put BETTER_AUTH_SECRET
npx wrangler types --env-interface CloudflareBindings # types c.env as CloudflareBindings

For local runs, set vars to http://localhost:5173 and http://localhost:8787 in .dev.vars (it overrides vars). On Bun and Node, the same five names go in the environment.

Another name, or a store read per request: charchySend({ apiKey: (c) => c.env.SEND_KEY }), or (c) => c.env.SEND_KEY.get() for a Secrets Store binding. The same goes for charchyWebhook(handlers, { secret }).

3. One app, many route files

The context type is declared once and shared by every new Hono<AppEnv>():

src/env.ts
import type { CharchySendVariables } from "@charchy/send/hono"
import type { auth } from "./auth"

type Session = typeof auth.$Infer.Session

export type AppEnv = {
  Bindings: CloudflareBindings // from `wrangler types`; leave Bindings out on Bun and Node
  Variables: CharchySendVariables & { user: Session["user"] | null; session: Session["session"] | null }
}

The middleware is registered once, on the app; route modules mounted with app.route() after it get c.var.charchySend:

src/app.ts
import { charchySend, charchyWebhook } from "@charchy/send/hono"
import { Hono } from "hono"
import { env } from "hono/adapter"
import { cors } from "hono/cors"
import { auth } from "./auth"
import type { AppEnv } from "./env"
import { invites } from "./routes/invites"
import { markUndeliverable } from "./users"

export const app = new Hono<AppEnv>()

// 1. Webhooks first, outside /api: no CORS, no session, nothing reads the body before it.
app.post(
  "/webhooks/charchy",
  charchyWebhook<AppEnv>({
    "email.bounced": (event) => markUndeliverable(event.data.recipient, `bounced: ${event.data.bounce.type}`),
    "email.complained": (event) => markUndeliverable(event.data.recipient, "complained"),
  })
)

// 2. CORS for the frontend, before every /api route.
app.use("/api/*", (c, next) =>
  cors({ origin: env<{ FRONTEND_ORIGIN: string }>(c).FRONTEND_ORIGIN, credentials: true })(c, next)
)

// 3. Better Auth at its basePath (/api/auth). The middleware below never runs for it.
app.all("/api/auth/*", (c) => auth.handler(c.req.raw))

// 4. Every other /api route: c.var.charchySend, c.var.user and c.var.session.
app.use("/api/*", charchySend())
app.use("/api/*", async (c, next) => {
  const session = await auth.api.getSession({ headers: c.req.raw.headers })
  c.set("user", session?.user ?? null)
  c.set("session", session?.session ?? null)
  await next()
})

// 5. Route modules, after the middleware they rely on.
app.route("/api/invites", invites)
src/index.ts
// Cloudflare Workers
import { app } from "./app"

export default app
  • Order is the contract. Hono runs middleware and handlers in the order they are registered: a use() after app.route() never runs for that module's routes, and a middleware after the handler that answers never runs at all — which is how Better Auth's routes skip the session lookup.
  • env(c) from hono/adapter reads c.env on Workers and process.env on Bun and Node, so FRONTEND_ORIGIN comes from wrangler.jsonc vars or the server's environment.
  • One client per key, kept across requests; the key is read on each request. With no key, c.var.charchySend is still set and its calls return missing_api_key, nothing sent.
  • charchySend({ variable: "mailer" }) names it c.var.mailer (CharchySendVariables<"mailer">). It also takes the client's options: maxRetries, timeoutMs, baseUrl, userAgent, fetch.

4. Send from a route

src/after-response.ts
import type { Context } from "hono"

/** Runs `task` once the response is out: Workers' waitUntil; Bun and Node keep running it. */
export function afterResponse(c: Context, task: () => Promise<unknown>): void {
  const running = task().catch((error: unknown) => console.error("after response:", error))
  try {
    c.executionCtx.waitUntil(running)
  } catch {
    // No ExecutionContext outside Workers: nothing to extend.
  }
}
src/routes/invites.ts
import { Hono } from "hono"
import { HTTPException } from "hono/http-exception"
import { afterResponse } from "../after-response"
import { FROM } from "../emails"
import type { AppEnv } from "../env"

export const invites = new Hono<AppEnv>()

invites.post("/", async (c) => {
  const user = c.var.user
  if (!user) throw new HTTPException(401)
  const { email } = await c.req.json<{ email: string }>()
  const inviteId = crypto.randomUUID() // in your app: the id of the invitation you just saved

  const { error } = await c.var.charchySend.emails.send(
    {
      from: FROM,
      to: email,
      replyTo: user.email,
      subject: `${user.name} invited you to My App`,
      html: `<p><a href="https://app.myapp.com/invite/${inviteId}">Accept the invitation</a></p>`,
      tags: { type: "invite" },
    },
    { idempotencyKey: `invite/${inviteId}` }
  )
  if (error) return c.json({ error: error.code }, error.code === "validation_error" ? 422 : 502)
  return c.json({ id: inviteId }, 201)
})

invites.post("/:id/accept", async (c) => {
  const user = c.var.user
  if (!user) throw new HTTPException(401)
  const inviteId = c.req.param("id")
  // …mark the invitation accepted, then answer without waiting on the email:
  afterResponse(c, async () => {
    const { error } = await c.var.charchySend.emails.send(
      { from: FROM, to: user.email, subject: "Welcome to My App", text: "You're in." },
      { idempotencyKey: `welcome/${inviteId}/${user.id}` }
    )
    if (error) console.error("welcome email", error.code, error.requestId)
  })
  return c.body(null, 204)
})
  • Idempotency keys come from the record (invite/<id>), so a retried request never sends twice. The SDK retries network errors, 5xx and 429 itself with the same key; calls resolve to { data, error } and never throw.
  • Await the send when the answer depends on it (the invite above). When it doesn't, afterResponse: on Workers the isolate is kept alive with waitUntil; Bun and Node keep running the promise. On Vercel, use waitUntil from @vercel/functions instead.
  • A code you send yourself gets expiresAt set to the code's own expiry, as in section 6.

5. Webhooks

charchyWebhook is the route in step 1 of src/app.ts. In the dashboard, under Webhooks, add https://api.myapp.com/webhooks/charchy.

AnswerWhen
204Verified, and its handler finished — or there is none for that type
400Fails verification (no detail is given)
500A handler threw, the secret is missing or malformed, or the raw body was already consumed — the event is sent again
  • Keep it out of /api/*. A session check would answer 401, and a middleware that consumes the body breaks the signature. A body read before it through c.req.text(), c.req.arrayBuffer() or c.req.json() (Hono 4.9+) is cached by Hono and still verifies; one read from c.req.raw is answered 500 with WebhookBodyUnavailableError, logged.
  • Each handler gets (event, c): the event typed by its type, and the context — c.env.DB, c.var. Give the generic (charchyWebhook<AppEnv>) to type c.
  • Handlers run before the answer, which must come within 5 seconds. Slow work goes to a queue, or c.executionCtx.waitUntil() on Workers — after 204, a failure there is not retried. Dedupe by event.id.
  • onError(error, event, c) hears every refusal and handler failure.

6. Better Auth with a separate frontend

Better Auth runs on the same app, at /api/auth/* (step 3 above). Its email codes go through Charchy Send:

src/emails.ts
import type { CharchySend } from "@charchy/send"
import { emailOTP } from "better-auth/plugins"

export const FROM = "My App <no-reply@myapp.com>" // on a domain verified in Charchy

const CODE_LIFETIME_SECONDS = 5 * 60

/** Better Auth's email-code plugin, sending through Charchy Send. */
export function emailCodes(send: CharchySend) {
  return emailOTP({
    expiresIn: CODE_LIFETIME_SECONDS,
    async sendVerificationOTP({ email, otp, type }) {
      // type: "sign-in" | "email-verification" | "forget-password" | "change-email"
      const { error } = await send.emails.send(
        {
          from: FROM,
          to: email,
          subject: `Your code: ${otp}`,
          text: `Your code is ${otp}. It expires in 5 minutes.`,
          html: `<p>Your code is <strong>${otp}</strong>. It expires in 5 minutes.</p>`,
          expiresAt: new Date(Date.now() + CODE_LIFETIME_SECONDS * 1000), // late codes are dropped and refunded
          tags: { type: `otp_${type.replaceAll("-", "_")}` },
        }
        // No idempotency key: every code is a new email, and the SDK keys its own retries.
      )
      if (error) throw error // Better Auth logs it; the person still sees "check your email"
    },
  })
}
src/auth.ts
// Cloudflare Workers
import { CharchySend } from "@charchy/send"
import { betterAuth } from "better-auth"
import { env, waitUntil } from "cloudflare:workers"
import { emailCodes } from "./emails"

export const auth = betterAuth({
  baseURL: env.BETTER_AUTH_URL, // "https://api.myapp.com"
  secret: env.BETTER_AUTH_SECRET,
  database: env.DB, // D1
  trustedOrigins: [env.FRONTEND_ORIGIN], // "https://app.myapp.com" — the same origin as CORS
  advanced: {
    backgroundTasks: { handler: waitUntil }, // emails go out after the response
    ipAddress: { ipAddressHeaders: ["cf-connecting-ip"] }, // per-client rate limits on Workers
  },
  plugins: [emailCodes(new CharchySend(env.CHARCHY_SEND_KEY))],
})
  • One instance, at module scope. On Workers, env and waitUntil from cloudflare:workers give the bindings outside a request, so auth is not rebuilt per request. Better Auth needs nodejs_compat (on by default from compatibility date 2026-08-04). Workers allow no I/O across requests: use D1 or a driver that queries over HTTP, not a pg or mysql2 pool.
  • backgroundTasks sends the email after the response, so a request's timing never shows whether an account exists. Without it Better Auth awaits the callback.
  • CORS and trustedOrigins name the same origin, explicitly: with credentials: true the origin can't be *, and Better Auth refuses requests from origins it doesn't trust (INVALID_ORIGIN). CORS is registered before the auth route.
  • The frontend: createAuthClient({ baseURL: "https://api.myapp.com" }). It sends credentials: "include" by default; a plain fetch to the API needs the same. With Hono RPC: hc<AppType>(url, { init: { credentials: "include" } }).

Cookies, by where the frontend lives:

Frontend → APICookies
app.myapp.com → api.myapp.comSame site: the default SameSite=Lax session cookie works. Add advanced.crossSubDomainCookies: { enabled: true, domain: "myapp.com" } only if the frontend's own server must read the session
myapp.com → myapp-api.workers.devCross-site: Safari blocks the cookie (ITP), other browsers increasingly. Serve the API under the frontend's domain, or proxy /api/* through the frontend's host (a Vercel rewrite, a Netlify redirect)
localhost:5173 → localhost:8787Same site (ports don't count): works in development

7. Try it

With a test key, nothing is sent or charged, and the magic addresses play out a known outcome:

npx wrangler dev                          # Workers, port 8787
bun src/index.ts                          # Bun, port 3000
npx tsx --env-file=.env src/index.ts      # Node.js, port 3000

curl -X POST http://localhost:8787/api/auth/email-otp/send-verification-otp \
  -H "Origin: http://localhost:5173" -H "Content-Type: application/json" \
  -d '{"email":"delivered@sim.charchy.krd","type":"sign-in"}'

The email shows on the dashboard's Emails page as delivered, tagged otp_sign_in. Sign in as bounced@sim.charchy.krd and the bounce reaches /webhooks/charchy as email.bounced (deployed, or through a tunnel such as cloudflared tunnel --url http://localhost:8787). In code, c.var.charchySend.test.address("bounced", "invite-test") builds the address; for tests that wait on the outcome, see Testing in CI.

Tests with app.request() pass bindings as the third argument: app.request("/api/invites", init, { CHARCHY_SEND_KEY: "chy_test_…" }). For a Worker that imports cloudflare:workers, run them in @cloudflare/vitest-pool-workers.

On this page