Skip to content
Tinbox

tutorials

Build a transactional email API with Hono on Cloudflare

September 9, 2026

#hono#cloudflare-workers#email-api#transactional-email#tutorial
Interlocking email tool modules illustrate a composable developer interface.

You need a single endpoint your app can POST to in order to send a receipt, a password reset, or a verification code. Hono on Workers is a great fit, but direct-to-MX port 25 is prohibited and Cloudflare's own SMTP endpoint is not reachable through Worker TCP. Here is the whole supported binding/HTTPS endpoint.

A transactional email API is deceptively small: one route, some auth, a bit of validation, and a send. The deceptive part is that each of those four pieces has a sharp edge. The auth check leaks timing if you write it naively. The validation has to reject the half-valid payloads your callers will absolutely send. The send can double-fire on a retry. And the actual delivery can't be done the way you'd do it on a normal Node server, because the Workers runtime won't let you.

Let's build the real thing with Hono, end to end, and be honest about every edge. Then, at the end, the shortcut if you'd rather not own the delivery layer yourself.

How do I build a transactional email API endpoint with Hono on Cloudflare Workers?

Define a POST /v1/send route on a Hono app, guard it with bearer-token middleware, validate the body with Zod, and forward the message to an HTTPS delivery layer. Hono is a thin router that runs on the Workers runtime with no Node dependencies, so it deploys as a single fetch handler. Here is the skeleton before we harden it:

npm create cloudflare@latest mailer -- --type hello-world
cd mailer
npm install hono zod
// src/index.ts
import { Hono } from "hono";

type Bindings = {
  SEND_TOKEN: string; // a Worker secret, set with: wrangler secret put SEND_TOKEN
};

const app = new Hono<{ Bindings: Bindings }>();

app.get("/health", (c) => c.json({ ok: true }));

app.post("/v1/send", async (c) => {
  const body = await c.req.json();
  // TODO: auth, validation, delivery
  return c.json({ accepted: true }, 202);
});

export default app;

That deploys and responds. It is also wide open, trusts any JSON, and doesn't actually send anything. We'll fix all three, in the order they bite.

How should I authenticate a transactional email API?

Use a bearer token in the Authorization header, store it as a Worker secret, and compare it in constant time. A send endpoint is a tempting target: anyone who can call it can send mail as you, which torches your domain reputation in an afternoon. So this check happens first, before you parse or validate anything.

The naive version is a single === comparison, and it has a real (if subtle) problem: string equality short-circuits on the first differing byte, so an attacker can measure response time to recover the token byte by byte. Compare lengths and bytes in fixed time instead.

import { Hono } from "hono";

type Bindings = { SEND_TOKEN: string };

const app = new Hono<{ Bindings: Bindings }>();

// Constant-time string compare. Returns false fast only on length mismatch.
function timingSafeEqual(a: string, b: string): boolean {
  const enc = new TextEncoder();
  const ab = enc.encode(a);
  const bb = enc.encode(b);
  if (ab.length !== bb.length) return false;
  let diff = 0;
  for (let i = 0; i < ab.length; i++) diff |= ab[i] ^ bb[i];
  return diff === 0;
}

// Gate everything under /v1/*
app.use("/v1/*", async (c, next) => {
  const header = c.req.header("authorization") ?? "";
  const [scheme, token] = header.split(" ");

  if (scheme !== "Bearer" || !token) {
    return c.json({ error: "missing_bearer_token" }, 401);
  }
  if (!timingSafeEqual(token, c.env.SEND_TOKEN)) {
    return c.json({ error: "invalid_token" }, 401);
  }
  await next();
});

Set the secret out of band, never in wrangler.jsonc:

npx wrangler secret put SEND_TOKEN
✔ Enter a secret value: ******************************
✨ Success! Uploaded secret SEND_TOKEN

Now an unauthenticated call fails cleanly:

curl -s -X POST https://mailer.you.workers.dev/v1/send -d '{}'
{"error":"missing_bearer_token"}

For a single app, one global token is fine. For a multi-tenant API, swap the secret comparison for a D1 lookup: hash the token, find the row, and read the tenant's allowed from domain off it. That way a leaked key can only send as the tenant it belongs to, not as anyone.

How do I validate the send request body?

Parse the body with a Zod schema and reject anything that isn't a complete, sendable message with 422. Callers will send you half-formed payloads: a to with no from, a subject and nothing else, an HTML body that's actually an object. Catch it at the door with a precise schema, not a pile of if statements.

The one rule that's easy to miss: a message needs a recipient, a sender, a subject, and at least one of html or text. Express that as a refinement.

import { z } from "zod";

const SendSchema = z
  .object({
    to: z.string().email(),
    from: z.string().email(),
    subject: z.string().min(1).max(255),
    html: z.string().optional(),
    text: z.string().optional(),
    replyTo: z.string().email().optional(),
  })
  .refine((m) => m.html != null || m.text != null, {
    message: "provide at least one of html or text",
    path: ["html"],
  });

type SendInput = z.infer<typeof SendSchema>;

app.post("/v1/send", async (c) => {
  let raw: unknown;
  try {
    raw = await c.req.json();
  } catch {
    return c.json({ error: "invalid_json" }, 400);
  }

  const parsed = SendSchema.safeParse(raw);
  if (!parsed.success) {
    return c.json(
      { error: "validation_failed", issues: parsed.error.flatten().fieldErrors },
      422,
    );
  }

  const message: SendInput = parsed.data;
  // delivery comes next
  return c.json({ accepted: true }, 202);
});

A bad payload now gets a useful error instead of a 500 from deep inside your send logic:

curl -s -X POST https://mailer.you.workers.dev/v1/send \
  -H "authorization: Bearer $SEND_TOKEN" \
  -H "content-type: application/json" \
  -d '{"to":"a@b.com","from":"me@you.com","subject":"Hi"}'
{"error":"validation_failed","issues":{"html":["provide at least one of html or text"]}}

Two judgment calls worth making explicitly. First, validate the from address against an allowlist of domains you actually control, not just "is it an email." Letting callers set an arbitrary from is how your API becomes an open relay. Second, cap body sizes (a few hundred KB of HTML is plenty) so a giant payload can't burn your CPU budget.

Why can't my Worker just connect to an SMTP server?

Cloudflare Workers prohibit outbound port 25, so a Worker cannot connect directly to recipient MX servers. Workers do expose outbound TCP to allowed third-party submission services, but Node SMTP packages are not automatically runtime-compatible. Cloudflare's own Email Service should be reached through its Worker binding or HTTPS API because Worker TCP cannot connect to Cloudflare-owned IP ranges.

Here is the version people try first, and exactly how it fails:

// This does NOT work on Cloudflare Workers.
import nodemailer from "nodemailer";

const transport = nodemailer.createTransport({
  host: "smtp.your-relay.com",
  port: 25,
  // ...
});

await transport.sendMail({ from, to, subject, html });
✘ [ERROR] Could not resolve "stream" / "net" / "tls"
  nodemailer relies on Node's net/tls sockets and the SMTP port.
  The Workers runtime blocks port 25 outbound; this transport can't connect.

Even with nodejs_compat shims, port 25 stays closed. Workers can make outbound fetch calls over HTTPS, and can open TCP sockets to allowed ports, but not the SMTP port. So edge email is delivered by handing the message to an HTTPS delivery layer that signs it (DKIM) and relays it onward. Your Hono endpoint's job ends at "validated message, accepted"; something downstream does the actual SMTP conversation off-platform. (For the full reasoning, see why edge email needs an HTTPS sender.)

So the send becomes an HTTPS call:

async function deliverOverHttps(
  message: SendInput,
  env: { DELIVERY_URL: string; DELIVERY_KEY: string; idempotencyKey: string },
): Promise<{ id: string }> {
  const res = await fetch(env.DELIVERY_URL, {
    method: "POST",
    headers: {
      authorization: `Bearer ${env.DELIVERY_KEY}`,
      "content-type": "application/json",
      "idempotency-key": env.idempotencyKey,
    },
    body: JSON.stringify(message),
  });

  if (!res.ok) {
    // Surface transient vs permanent so the caller (or a queue) can decide to retry.
    throw new Error(`delivery_failed:${res.status}`);
  }
  return (await res.json()) as { id: string };
}

If you want this delivery to be durable under load rather than inline in the request, push the validated message onto a queue here instead of awaiting the HTTPS call. That's a separate concern with its own sharp edges, covered in sending email reliably at volume with Queues and distilled into the Cloudflare Queues patterns for reliable sending.

How do I stop the API from sending duplicate emails?

Accept an Idempotency-Key header, store processed keys with their result, and replay the original response when the same key returns. Clients retry. A network hiccup hides your 202, the client fires the same request again, and now your user has two password-reset emails and one of the links is dead. Idempotency makes the retry a no-op.

Bind a KV namespace for the key store in wrangler.jsonc:

{
  "name": "mailer",
  "main": "src/index.ts",
  "compatibility_date": "2026-06-01",
  "kv_namespaces": [
    {
      "binding": "IDEMPOTENCY",
      "id": "<your-kv-id>",
    },
  ],
}

Then check it before delivering and record it after:

type Bindings = {
  SEND_TOKEN: string;
  DELIVERY_URL: string;
  DELIVERY_KEY: string;
  IDEMPOTENCY: KVNamespace;
};

app.post("/v1/send", async (c) => {
  const idemKey = c.req.header("idempotency-key");

  if (idemKey) {
    const prior = await c.env.IDEMPOTENCY.get(idemKey);
    if (prior) {
      // Same request already accepted: return the original result, don't resend.
      return c.json({ accepted: true, id: prior, replayed: true }, 202);
    }
  }

  const raw = await c.req.json().catch(() => null);
  const parsed = SendSchema.safeParse(raw);
  if (!parsed.success) {
    return c.json(
      { error: "validation_failed", issues: parsed.error.flatten().fieldErrors },
      422,
    );
  }

  const { id } = await deliverOverHttps(parsed.data, {
    DELIVERY_URL: c.env.DELIVERY_URL,
    DELIVERY_KEY: c.env.DELIVERY_KEY,
    idempotencyKey: idemKey ?? crypto.randomUUID(),
  });

  if (idemKey) {
    // Keep the mapping long enough to cover a client's retry window.
    await c.env.IDEMPOTENCY.put(idemKey, id, { expirationTtl: 60 * 60 * 24 });
  }

  return c.json({ accepted: true, id }, 202);
});

A real race remains: two concurrent requests with the same key can both miss the get before either put. If you need strict once-only semantics, move the check into your delivery layer and pass the key through as an Idempotency-Key header (most delivery APIs dedupe on it server-side), which is what deliverOverHttps already does. KV gives you cheap best-effort dedupe at the edge; the delivery layer gives you the authoritative guarantee.

Common failure modes (and what they mean)

401 invalid_token on a request you're sure is correct

The Authorization header is probably Bearer<space><token> with an extra space, or you set the secret with a trailing newline. Re-run wrangler secret put SEND_TOKEN and paste the value without a newline.

delivery_failed:451 or delivery_failed:429

Transient: the delivery layer rate-limited or had a hiccup. Don't return this as a 5xx the client should give up on. Either retry with backoff or enqueue, and surface a 202 to the caller.

Mail sends but lands in spam

The endpoint is fine; this is an authentication/reputation problem downstream. Confirm DKIM is signing and your SPF and DMARC records are aligned. Start with the SPF, DKIM, and DMARC setup guide.

The same user got two receipts

You're not threading an Idempotency-Key through, or your client generates a new key per attempt. Generate the key once at the call site (per logical send), not per HTTP attempt.

The shortcut: skip the delivery layer entirely

Everything above is the correct shape of a transactional email API, and it's genuinely useful to understand. But notice what we waved at in deliverOverHttps: a signing-and-relaying delivery layer that does DKIM, talks SMTP off-platform, records bounces, and dedupes. Building that is the actual work. The Hono routing is the easy 20%.

This is where Tinbox fits. It deploys the delivery layer (and the queue, and the bounce tracking, and DKIM signing) into your own Cloudflare account, so your Hono endpoint shrinks to one call with no third-party SaaS in the path and no per-email pricing:

npx tinbox init yourdomain.com
import { Hono } from "hono";
import { tinbox } from "tinbox/cf";

const app = new Hono<{ Bindings: Env }>();

app.post("/v1/send", async (c) => {
  const { to } = await c.req.json<{ to: string }>();
  const { id } = await tinbox(c.env).send({
    to,
    from: "hi@yourdomain.com",
    subject: "Welcome",
    html: "<p>Thanks for signing up.</p>",
  });
  return c.json({ accepted: true, id }, 202);
});

export default app;

tinbox(env).send() enqueues the message, hands it to the configured binding or HTTPS transport, and tracks the result on infrastructure you own and can read. You keep your Hono routes, auth, and validation exactly as built above; you just stop maintaining the part that's hard to get right.

If you're weighing owning this against paying a hosted API to run it, here's an honest comparison, and the cost math once volume climbs. Building on Next.js rather than raw Hono? See sending from Next.js on Cloudflare, or the wider set of framework guides for sending email on Cloudflare if your stack is something else entirely.

Deploy this yourself: npx tinbox init yourdomain.com. The full sender, queue, and DKIM configuration is in the Tinbox docs.

Frequently asked questions

How do I build a transactional email API endpoint with Hono on Cloudflare Workers?

Create a Hono app, add a POST /v1/send route, protect it with bearer-token middleware that compares the key in constant time, validate the JSON body with a Zod schema (to, from, subject, and one of html/text), then forward the message to a delivery layer over HTTPS. Return 202 Accepted with a message id. Workers cannot open outbound port 25 for direct-to-MX SMTP, so the actual delivery is an HTTPS call, not a port-25 connection.

Why can't a Cloudflare Worker send email over SMTP directly?

Workers prohibit outbound port 25, so they cannot deliver directly to recipient MX servers. They do expose outbound TCP to allowed third-party submission services, while Cloudflare Email Service is reached from Workers through its native binding or HTTPS API. This example uses the binding/HTTPS path so policy, DKIM, and tracking stay in one delivery layer.

How should I authenticate a transactional email API?

Use a bearer token in the Authorization header, stored as a Worker secret, and compare it in constant time so the check does not leak the key through timing. Reject missing or malformed headers with 401 before any work happens. For multi-tenant setups, look the token up in D1 and scope it to an allowed from-domain rather than using one global key.

How do I stop a transactional email API from sending duplicates?

Require or accept an Idempotency-Key header, store processed keys (in KV or D1) with the resulting message id, and return the original response if the same key arrives again. This makes client retries safe: a network blip that hides your 202 won't cause a second receipt or password-reset email to go out.

Should a send endpoint return 200 or 202?

Return 202 Accepted if delivery happens asynchronously (enqueued and sent by a consumer), because you have accepted the message but not yet delivered it. Return 200 only if you actually completed delivery before responding. Being precise here keeps your API contract honest and lets clients reason about retries.