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.
| Runtime | Read from | Local | Production |
|---|---|---|---|
| Cloudflare Workers | c.env binding | .dev.vars | npx wrangler secret put CHARCHY_SEND_KEY |
| Bun | process.env | .env (Bun loads it) | The host's environment |
Node.js (@hono/node-server) | process.env | --env-file=.env | The host's environment |
| Deno, Supabase Edge Functions, Netlify Edge | process.env / Deno.env (needs --allow-env) | deno run --env-file --allow-env | The platform's secrets |
| Vercel, AWS Lambda | process.env | .env | Project / function environment variables |
| Lambda@Edge, Fastly Compute | No environment variables | — | Pass apiKey (below) |
On Workers, everything this guide uses:
{
"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" }
}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 CloudflareBindingsFor 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>():
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:
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)// 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()afterapp.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)fromhono/adapterreadsc.envon Workers andprocess.envon Bun and Node, soFRONTEND_ORIGINcomes fromwrangler.jsoncvarsor the server's environment.- One client per key, kept across requests; the key is read on each
request. With no key,
c.var.charchySendis still set and its calls returnmissing_api_key, nothing sent. charchySend({ variable: "mailer" })names itc.var.mailer(CharchySendVariables<"mailer">). It also takes the client's options:maxRetries,timeoutMs,baseUrl,userAgent,fetch.
4. Send from a route
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.
}
}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,5xxand429itself 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 withwaitUntil; Bun and Node keep running the promise. On Vercel, usewaitUntilfrom@vercel/functionsinstead. - A code you send yourself gets
expiresAtset 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.
| Answer | When |
|---|---|
204 | Verified, and its handler finished — or there is none for that type |
400 | Fails verification (no detail is given) |
500 | A 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 answer401, and a middleware that consumes the body breaks the signature. A body read before it throughc.req.text(),c.req.arrayBuffer()orc.req.json()(Hono 4.9+) is cached by Hono and still verifies; one read fromc.req.rawis answered500withWebhookBodyUnavailableError, logged. - Each handler gets
(event, c): the event typed by itstype, and the context —c.env.DB,c.var. Give the generic (charchyWebhook<AppEnv>) to typec. - Handlers run before the answer, which must come within 5 seconds. Slow
work goes to a queue, or
c.executionCtx.waitUntil()on Workers — after204, a failure there is not retried. Dedupe byevent.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:
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"
},
})
}// 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,
envandwaitUntilfromcloudflare:workersgive the bindings outside a request, soauthis not rebuilt per request. Better Auth needsnodejs_compat(on by default from compatibility date2026-08-04). Workers allow no I/O across requests: use D1 or a driver that queries over HTTP, not apgormysql2pool. backgroundTaskssends 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
trustedOriginsname the same origin, explicitly: withcredentials: truethe 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 sendscredentials: "include"by default; a plainfetchto the API needs the same. With Hono RPC:hc<AppType>(url, { init: { credentials: "include" } }).
Cookies, by where the frontend lives:
| Frontend → API | Cookies |
|---|---|
app.myapp.com → api.myapp.com | Same 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.dev | Cross-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:8787 | Same 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.