← Back to blog

Fastify Transactional Email API (2026): A Plugin That Posts to /emails

Send transactional email from Fastify with Rovela’s HTTP API: a plugin that uses fetch, environment configuration for the Bearer key, Idempotency-Key, and documented errors. Not a NestJS or Express OTP rewrite.

Updated November 10, 2026
Fastify Transactional Email API (2026): A Plugin That Posts to /emails

Fastify already speaks HTTP; transactional email should too

A Fastify application already posts JSON, talks to payment providers, and returns a booking confirmation. The natural way to send transactional email — a booking confirmation, a “your export is ready” note, a shipping update, a security alert — is the same pattern: one HTTPS POST with a Bearer key, not Nodemailer pointed at a mailbox.

Rovela’s Email API is built for that. There is no official SDK and no npm package you have to treat as first-party. 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 NestJS transactional rewrite, not an Express OTP guide, and not a Node.js language tour. Everyday Nest sending already has its own post (NestJS transactional email API). Express coverage in the inventory is an OTP guide, which this article will not redo. If you only wanted a first request in Node syntax, start from Node.js email API or send email in Node.js. This article is everyday Fastify app mail: a plugin that decorates fastify.emails, environment variables for the key, an Idempotency-Key on anything a retry might repeat, and documented error handling around the {statusCode, name, message} envelope.

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 Fastify process belongs on POST /emails. If you were about to reach for Nodemailer as the default, the Nodemailer alternative post explains why the HTTP API is the better fit for app volume.

A Fastify route calls a plugin decorator that posts JSON to the email API and receives a message id

What you need before the first Fastify send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or Node’s built-in fetch:

  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 "Acme <hello@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 Fastify plugin that uses fetch

Keep the key on the server. Never put a Rovela key in a browser bundle, a mobile app, or a public repository. A leaked sending_access key can send mail as your domain. Environment variables read when the plugin is registered are the right place in a Fastify process.

The plugin below uses Node’s built-in fetch (Node 18+) so you do not add a second HTTP client just to send mail. If you already use undici directly, the JSON body and headers are identical. There is still no official SDK to install.

// plugins/emails.js
import fp from 'fastify-plugin'

class EmailsError extends Error {
  constructor(statusCode, payload) {
    super(payload?.message || `HTTP ${statusCode}`)
    this.statusCode = statusCode
    this.payload = payload // {statusCode, name, message}
  }
}

async function emailsPlugin(fastify, opts) {
  const baseURL = (process.env.ROVELA_BASE_URL || 'https://api.rovela.dev').replace(/\/$/, '')
  const apiKey = process.env.ROVELA_API_KEY // sending_access
  const from = process.env.ROVELA_FROM || 'Acme <hello@mail.acme.com>'

  async function send({ to, subject, html, text, replyTo, tags, idempotencyKey }) {
    const body = { from, to, subject, html, text }
    if (replyTo) body.reply_to = replyTo
    if (tags !== undefined) body.tags = tags

    const headers = {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    }
    if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey

    const res = await fetch(`${baseURL}/emails`, {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(30_000),
    })
    const payload = await res.json()
    if (!res.ok) {
      throw new EmailsError(res.status, payload)
    }
    return payload // {"object":"email","id":"..."}
  }

  fastify.decorate('emails', { send })
}

export default fp(emailsPlugin, { name: 'emails' })

Register it once, then call fastify.emails.send from any route. The documented success body is {"object": "email", "id": "9f1c2e40-..."}. Store that id on the booking or export job. Do not invent other response fields.

The same request in curl is useful when you are checking the domain and the key before you wire the plugin:

curl -X POST https://api.rovela.dev/emails \
  -H "Authorization: Bearer re_your_api_key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: booking-bk_1042" \
  -d '{
    "from": "Acme <hello@mail.acme.com>",
    "to": "alice@example.com",
    "subject": "Your booking is confirmed",
    "html": "<p>Booking BK-1042 is confirmed.</p>",
    "text": "Booking BK-1042 is confirmed."
  }'

A route that sends after the booking is saved

Call the plugin after the work that matters has already succeeded — the booking row is persisted, the export file is in object storage, the shipment is marked dispatched. If the route should return quickly, enqueue the send and reuse the same Idempotency-Key whenever that job is retried. The header may be up to 256 characters and is remembered for 24 hours (Idempotency-Key).

// routes/bookings.js
export default async function bookingRoutes(fastify) {
  fastify.post('/bookings', async (request, reply) => {
    const booking = await saveBooking(request.body) // already committed
    const result = await fastify.emails.send({
      to: booking.email,
      subject: 'Your booking is confirmed',
      html: `<p>Booking ${booking.id} is confirmed.</p>`,
      text: `Booking ${booking.id} is confirmed.`,
      replyTo: 'reservations@mail.acme.com',
      tags: { kind: 'booking_confirmation', bookingId: booking.id },
      idempotencyKey: `booking-${booking.id}`,
    })
    return { bookingId: booking.id, emailId: result.id }
  })
}

tags are optional labels returned with the message; they are not a substitute for Idempotency-Key and they are not topic_id. The Email API tags guide covers the documented shapes. reply_to is the right field when a human should be able to answer; see Email API reply-to. Recipients across to, cc, and bcc are capped at 50, and quota is charged per recipient (cc and bcc).

Do not invent a sandbox. Free-plan keys send real mail. During development, use a verified staging subdomain and recipients you control (how to test a transactional email API).

Errors you should handle in the plugin

Every error uses the same shape (Quick Start, Email API error handling):

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

Documented cases you will actually hit from a Fastify route:

  • 400 — a missing required field, an unverified or foreign from domain, a template that does not exist, a base64 attachment that does not decode, or more than 50 recipients across to, cc, and bcc.
  • 401 — missing or invalid key, or a sending_access key used to read, reschedule, or cancel a message. Reading events is a full_access (or session) operation.
  • 429 — rate limit exceeded. Each entry in a batch counts individually, so a large batch can trip this partway through.

Surface the message field in your own logs as-is. Do not invent a /logs API; delivery history lives in the dashboard and, with a full_access key, on GET /emails/:id and GET /emails/:id/events.

A 403 can appear on management endpoints when the credential is valid but lacks permission — for example, a sending_access key used against the Domains API. That is a different failure from a 401. See Email API authentication and the sending domains API guide in this batch.

Nodemailer or mailbox SMTP is send-as-self and capped; a Fastify process should POST /emails and watch delivery on a webhook

Delivery is asynchronous — do not poll from the request path

A 200 from POST /emails is not a delivery receipt. Confirm later:

  • The Emails view in the dashboard.
  • GET /emails/:id and GET /emails/:id/events with a full_access key. You are looking for accepted, delivered, or bounced events on that message (Email delivery status API).
  • A webhook for anything in production. Verify the HMAC-SHA256 signature (webhook security). Event types include sent, delivered, delayed, bounced, complained, opened, and clicked.

Do not turn a Fastify route into a polling loop against /emails/:id/events. The docs are explicit: the events endpoint is useful for debugging a single message; systematic handling belongs on a webhook. If you already expose a webhook route in the same Fastify app, verify the signature before you trust the body.

POST /emails/batch accepts up to 100 messages, each with the same schema, processed independently. template and topic_id are rejected on the batch endpoint rather than ignored — send those through POST /emails. If you schedule with scheduled_at, reading, rescheduling, and cancelling need full_access or a dashboard session; a sending_access key can only send. The dedicated scheduled email and batch transactional email guides cover those flows in full; this article will not redo them.

Templates are available if you would rather store HTML in Rovela and send { id, variables } (Templates API, templates guide). template is mutually exclusive with html and text. You can also render HTML in the Fastify process and pass the resulting strings as html and text — that is ordinary Node, not a Rovela SDK.

What not to do in a Fastify codebase

Do not point Nodemailer at mx.rovela.dev and send application volume that way. That path is for mailboxes and mail apps. A mailbox can send only as its own address, and the documented client limit is 30 messages a minute. You also lose the HTTP API’s tracking, logs, and webhooks (SMTP, Email API vs SMTP relay).

Do not create a “Rovela SDK” plugin that invents endpoints, official clients, numeric HTTP rate (req/s) figures, a sandbox flag, or a dedicated IP. Call the documented HTTP API with fetch.

Do not put the key in query parameters, in frontend code, or in a committed .env that ships to git. Create a sending_access key for the Fastify service. If you send for several customers from one organization, a key can be restricted to a single domain (Authentication, Email API for multi-tenant SaaS).

Do not treat a fire-and-forget setImmediate as a substitute for idempotency. A background call that retries after a timeout still needs an Idempotency-Key. A background call also does not confirm delivery; only the events API or a webhook does. For retry policy around timeouts and 429s, see Email API retries. This is also not a Bun runtime guide; if you are on Bun, see the existing Bun transactional email post.

A compact Fastify checklist

  1. Verify the sending domain before any production from.
  2. Store a sending_access key in the environment; construct Authorization: Bearer … in the plugin.
  3. Send both html and text. Set reply_to when a human should be able to answer.
  4. Put an Idempotency-Key on any send a queue, payment webhook, or double submit might repeat.
  5. Handle 400, 401, and 429 from the documented error envelope. Remember that 200 means queued.
  6. Store the returned message id on the booking or export job.
  7. Subscribe to webhooks for delivery, bounces, and complaints; use GET /emails/:id/events only to debug a single message.
  8. Leave mailbox SMTP to people and mail apps.

Once that plugin is in place, every other Fastify route can call it the same way — receipts, security alerts, “your export is ready” notes — without growing a second email stack. That is the point of a transactional email API: one authenticated HTTP call from the application you already run. For a first request without Fastify at all, the curl sending guide and HTTP email API pages are the shortest path.