← Back to blog

Koa Transactional Email API (2026): Send a Weekly Digest from Middleware with POST /emails

Send transactional email from Koa with Rovela’s HTTP API: a ctx helper or middleware, environment variables for the Bearer key, a weekly-digest-ready notice, and Idempotency-Key. Clearly Koa — not an Express OTP rewrite.

Updated November 10, 2026
Koa Transactional Email API (2026): Send a Weekly Digest from Middleware with POST /emails

Koa already gives you ctx and middleware; transactional email belongs in a helper, not in an Express OTP rewrite

A Koa app is a stack of async middleware around a ctx object. The work that needs a secret belongs there, or in a helper that middleware attaches to ctx, where an environment variable can stay private. Transactional email — “your weekly digest is ready,” a recap that just finished rendering, a link to this week’s edition — is that kind of work. The natural way to send it is one HTTPS POST with a Bearer key from your own Koa helper, not an SMTP session, and not a port of an Express one-time-code tutorial.

Rovela’s Email API is built for that. There is no client library to install and no official Rovela-Koa middleware in the public docs. Do not look for one in this guide. The base URL is https://api.rovela.dev. You authenticate with Authorization: Bearer re_… (Authentication) and queue a message with POST /emails. The response is a message id. HTTP 200 means the message was accepted and queued, not that it has already arrived (Quick Start).

This is not a redo of a one-time passcode tutorial, and it is not a contacts, topics, or broadcasts product tour. It is everyday app mail from Koa server code: a ctx helper, environment variables for the key, a route that sends after a weekly digest is ready, an Idempotency-Key on anything a retry or a double dispatch might repeat, and documented error handling around the {statusCode, name, message} envelope. Nearby Node walkthroughs such as Hono, Fastify, Elysia, AdonisJS, and sending email in Node.js cover those stacks. There is an Express OTP guide; this article is not a rewrite of it. The shape here is Koa: ctx, onion middleware, and a digest — not a login code.

If you are still choosing between HTTP and SMTP, read Email API vs SMTP. Rovela’s SMTP is mailbox SMTP for mail apps (mx.rovela.dev:465, a device credential, send-as-self, 30 messages a minute from one client address). Programmatic volume from a Koa process belongs on POST /emails.

Koa middleware attaches a ctx emails helper; a weekly-digest route posts JSON to the email API

What you need before the first Koa send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch inside a Koa helper:

  1. Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
  2. Add and verify a sending domain (a subdomain such as mail.example.com is a common choice). You cannot send from a domain you have not verified; an unverified or foreign from is refused with a 400 that names the domain. See the domain setup guide and what domain email is.
  3. Create an API key. A sending_access key can send and nothing else — the right default for production. A full_access key can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once.
  4. Send with POST /emails.
  5. Confirm delivery in the dashboard, with GET /emails/:id or GET /emails/:id/events (those reads need full_access or a dashboard session), or with a webhook.

from is a string in the documented form "Digest <editorial@yourdomain.com>". The address must sit on a verified sending domain. That is the same rule that makes domain email trustworthy: you prove you control the domain before you speak as it. How the display name and the address work is covered in the From name guide.

At least one of html, text, or template is required. Send both html and text where you can — many clients preview the text part (HTML email API).

A ctx helper, middleware, and environment variables

Keep the key on the server. Never put it on ctx.state in a way that a later middleware serializes it into a public JSON body, never return it from a route, and never commit it to a repository. A leaked sending_access key can send mail as your domain.

Private values belong in .env and are read through process.env when the helper is constructed. A missing key should fail when the helper is first used, not halfway through dispatching a digest. The Koa way to share it is middleware that hangs a function on ctx (or app.context) so routes stay thin.

# .env (server only; never commit the live key)
ROVELA_API_KEY=re_your_sending_key
ROVELA_FROM=Digest <editorial@mail.example.com>
// src/emails.js
class ApiError extends Error {
  constructor({ statusCode, name, message }) {
    super(message || `Rovela: HTTP ${statusCode}`)
    this.statusCode = statusCode
    this.name = name || 'ApiError'
  }
}

function requireEnv(name) {
  const value = process.env[name]
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`)
  }
  return value
}

async function sendEmail({ to, subject, html, text, replyTo, tags, idempotencyKey }) {
  const apiKey = requireEnv('ROVELA_API_KEY')
  const from = requireEnv('ROVELA_FROM')
  const headers = {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  }
  if (idempotencyKey) {
    headers['Idempotency-Key'] = idempotencyKey
  }

  const body = { from, to, subject }
  if (html) body.html = html
  if (text) body.text = text
  if (replyTo) body.reply_to = replyTo
  if (tags) body.tags = tags

  const res = await fetch('https://api.rovela.dev/emails', {
    method: 'POST',
    headers,
    body: JSON.stringify(body),
  })

  const payload = await res.json().catch(() => ({}))
  if (!res.ok) {
    throw new ApiError({
      statusCode: Number(payload.statusCode || res.status),
      name: payload.name,
      message: payload.message,
    })
  }
  return payload
}

function emailsMiddleware() {
  return async (ctx, next) => {
    ctx.sendEmail = sendEmail
    await next()
  }
}

module.exports = { sendEmail, ApiError, emailsMiddleware }
// src/app.js
const Koa = require('koa')
const { emailsMiddleware } = require('./emails')

const app = new Koa()
app.use(emailsMiddleware())
// body parser and router follow in the onion: they see ctx.sendEmail

The helper uses the platform fetch already available in a current Node runtime, so the module does not need a second HTTP client just to send mail. The JSON body and headers are the same ones the Emails API documents. Only server middleware and routes should call ctx.sendEmail.

A route that sends when the weekly digest is ready

A ready digest is a good everyday example because it is not a login code and it is easy to double-send: a publisher clicks Send twice, a queue worker retries the job, or two Koa instances pick up the same week. Put the send behind a Koa route (or a worker that imports the same helper), and give every edition a stable Idempotency-Key that includes the week id and the subscriber id. An Idempotency-Key may be up to 256 characters; a retry of the same request within 24 hours returns the original response instead of sending again (idempotency).

The sketch below uses @koa/router. This is still your code calling POST /emails. It is not a Rovela plugin, and it is not an Express req/res handler pasted into Koa.

// src/routes/digests.js
const Router = require('@koa/router')
const { ApiError } = require('../emails')

const router = new Router()

router.post('/digests/:week/send', async (ctx) => {
  const week = ctx.params.week
  const { subscriberEmail, subscriberId, editionTitle, editionUrl } = ctx.request.body || {}

  if (!week || !subscriberEmail || !subscriberId) {
    ctx.status = 400
    ctx.body = { error: 'week, subscriberEmail, and subscriberId are required' }
    return
  }

  // Persist the dispatch in your own store, then send.
  // This guide does not invent a Rovela “contacts” or newsletter API.

  try {
    const result = await ctx.sendEmail({
      to: subscriberEmail,
      subject: 'Your weekly digest is ready',
      html: `<p><b>${editionTitle}</b> is ready.</p><p><a href="${editionUrl}">Read this week</a></p>`,
      text: `${editionTitle} is ready: ${editionUrl}`,
      tags: { purpose: 'weekly-digest', week, subscriber_id: String(subscriberId) },
      idempotencyKey: `weekly-digest:${week}:${subscriberId}`,
    })
    ctx.body = { status: 'ok', emailId: result.id }
  } catch (err) {
    if (err instanceof ApiError) {
      ctx.status = 200
      ctx.body = { status: 'ok', emailError: err.message }
      return
    }
    throw err
  }
})

module.exports = router

editionTitle and editionUrl are your domain fields. This article does not invent a Rovela digest API — store the edition however your app already does, then pass the subscriber address to POST /emails. If a worker rather than an HTTP route renders the digest, import sendEmail directly; you do not need ctx in a background job, but the helper stays the same.

If you later need many personalized messages in one go — one request per week, up to 100 subscribers at a time — use batch (POST /emails/batch, up to 100 messages, each processed independently). template and topic_id are rejected on batch rather than ignored; send those through POST /emails.

Errors you should handle in the helper

Every documented error uses the same envelope, so one ApiError covers them (Quick Start, Email API error handling):

{ "statusCode": 400, "name": "Bad Request", "message": "html or text body is required" }

The message says what was wrong. Surface it in your Koa logs as-is.

  • 400 — a missing required field, a base64 attachment that does not decode, a from domain that does not belong to your organization, a template that does not exist, or more than 50 recipients on one message.
  • 401 — missing or invalid credential, or a sending_access key used to read, reschedule, or cancel a message.
  • 429 — rate limit exceeded. The first-email guide notes that the rate limit is per key, and that each message in a batch counts individually. The official batch example waits on Retry-After when that header is present (and falls back to one second if it is not). This article will not invent a requests-per-second number, because the public docs do not publish one.

HTTP 200 on send is not delivery. If you need to look a message up later, GET /emails/:id and GET /emails/:id/events require a full_access key or a dashboard session — do not put that key in the same helper you call from every digest dispatch. Managing sending domains is a different API and a different key scope (Domains API, Email API authentication, sending domains API). A sending_access key used on a management endpoint such as GET /domains is documented as 403; that is not the same as a failed send.

A route should not fail the digest record just because mail queued slowly. Log the error, keep the edition marked ready, and let your webhook or a later retry (with the same idempotency key) finish the notice.

Delivery is asynchronous — do not poll from the middleware

The route should record the message id and return. Confirm delivery in the dashboard, with the Email delivery status API, or with a webhook. For production, prefer a webhook over polling GET /emails/:id from the send handler. A digest request should not wait on inbox arrival.

A webhook endpoint in Koa is another POST route that reads the raw body (disable JSON parsing for that path, or capture the raw buffer first), verifies x-resend-signature, and returns 2xx quickly. Verification is byte-exact HMAC-SHA256 over "<timestamp>.<raw body>" (webhook security). A 400 you return because a payload surprised you is a permanent loss; store anything you do not yet understand rather than rejecting it. Deduplicate on the event id. Managing webhook endpoints themselves is covered in the Email Webhooks API guide and the signature verification walkthrough.

When you need a message to go out later — a Sunday morning send — use scheduled_at (scheduled email). POST /emails/:id/cancel can cancel a message that has not been sent yet; reading, rescheduling, and cancelling need a full_access key or a dashboard session. Public docs do not describe a reschedule request body, so this article will not invent one. When you need many sends in one request, use batch transactional email. Reusable layouts belong in the Templates API and the templates guide.

An Express-style OTP handler is the wrong tutorial; a Koa ctx helper posts a weekly digest to the email API

What not to do in a Koa codebase

Do not invent a Rovela-Koa plugin, a dashboard click path that is not in the docs, or a special digest object Rovela would have to provide. This integration is plain HTTP from your server code.

Do not paste an Express req/res OTP handler into a Koa file and call it done. Koa’s contract is ctx and await next(). If you needed a login code, that is a different article; this one is a weekly digest.

Do not point Nodemailer or any other SMTP client at Rovela mailbox SMTP and call that your application mailer. Mailbox SMTP is for mail apps: a mailbox can send only as itself, and a single client address is limited to 30 messages a minute. That is the wrong default for app volume, which is the point of Email API vs SMTP relay as well.

Do not put a Rovela key in a public asset or a repository. Call the API from middleware, a route, or a job that only runs on the server. Authentication is explicit: a browser bundle is readable by anyone who has it.

Do not treat this guide as a replacement for an OTP article, and do not treat it as a broadcast or contacts tour. Public docs for contacts, topics, segments, and broadcasts are not used as a product walkthrough here. This helper is for the mail your Koa app sends after an editorial event — a digest that is ready, an edition that was updated, a notice that a new issue is up.

Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your Koa process should not share a device credential with someone else’s Thunderbird profile.

If you send on behalf of several publications from one organization, restrict a key to a single domain so a leak cannot send as somebody else (Email API for multi-tenant SaaS). Retries of a failed HTTP call should reuse the same idempotency key (Email API retries).

If you later compare providers, the documented pages include Rovela vs Resend, vs SendGrid, vs Postmark, vs Mailgun, vs Brevo, and vs Amazon SES.

A compact Koa checklist

  • Verify the sending domain before you set from. An unverified domain is a 400, not a silent drop.
  • Keep ROVELA credentials in server environment variables and attach the helper to ctx from middleware, not from a public route body.
  • Prefer a sending_access key in production digest routes; keep full_access for tooling that reads events or manages webhooks.
  • Send both html and text when you can, and set an Idempotency-Key on any path a retry or a double dispatch can hit twice.
  • Record the message id and return from the route. Do not fail the digest record because mail is still queueing. Watch delivery with a webhook, not a loop in the middleware.
  • If you need a first request in curl, use the transactional email API overview, the curl sending guide, or the HTTP email API explainer — then come back to this helper for the Koa shape.