← Back to blog

Astro Transactional Email API (2026): Send App Mail from an On-Demand Endpoint with POST /emails

Send transactional email from Astro with Rovela’s HTTP API: an on-demand server endpoint, server-only environment variables for the Bearer key, and Idempotency-Key. Not a magic-link tutorial.

Updated November 10, 2026
Astro Transactional Email API (2026): Send App Mail from an On-Demand Endpoint with POST /emails

Astro can stay mostly static; transactional email still needs an on-demand endpoint

An Astro site can pre-render almost every page and still have a small server surface: an endpoint under src/pages/api, with prerender = false, that runs only when a request arrives. Transactional email — “your event registration is confirmed,” a download that is ready, a form the static site cannot send by itself — is that kind of work. The natural way to send it is one HTTPS POST with a Bearer key, not a mailbox SMTP session, and not a third-party form-forwarding hack that leaves your domain out of the from address.

Rovela’s Email API is built for that. There is no official SDK and no Astro integration you have to pin just to send mail. 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 passwordless login tutorial. If you need a one-time sign-in link, start from the existing Astro magic link guide. This article is everyday app mail from an on-demand endpoint: server-only environment variables for the key, a POST handler that sends after a registration is confirmed, an Idempotency-Key on anything a retry might repeat, and documented error handling around the {statusCode, name, message} envelope. It is also not a SvelteKit or Next.js rewrite — those everyday-send shapes already live in the SvelteKit transactional email guide and send email in Next.js.

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 an Astro endpoint belongs on POST /emails.

An on-demand Astro endpoint calls a server-only emails module that posts JSON to the email API and receives a message id

What you need before the first Astro send

The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch inside an Astro endpoint:

  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).

An on-demand Astro endpoint also needs a server adapter in production (Node, or the adapter your host documents). A fully static build has nowhere to run POST /emails. That is an Astro deployment fact, not a Rovela product limit.

A server-only module and an on-demand endpoint

Keep the key on the server. In Astro, environment variables without the PUBLIC_ prefix stay off the client. Never name the variable PUBLIC_ROVELA_API_KEY, never import the helper from a frontmatter block that hydrates a client component, and never call api.rovela.dev from a <script>. A leaked sending_access key can send mail as your domain.

This helper uses the platform fetch already available in an Astro endpoint, 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.

// src/lib/emails.ts
const BASE_URL = 'https://api.rovela.dev';

export class ApiError extends Error {
  statusCode: number;
  name: string;
  constructor({ statusCode, name, message }: { statusCode: number; name?: string; message?: string }) {
    super(message || `Rovela: HTTP ${statusCode}`);
    this.statusCode = statusCode;
    this.name = name || 'ApiError';
  }
}

export async function sendEmail({
  to,
  subject,
  html,
  text,
  replyTo,
  tags,
  idempotencyKey
}: {
  to: string | string[];
  subject: string;
  html?: string;
  text?: string;
  replyTo?: string | string[];
  tags?: Record<string, string> | Array<{ name: string; value: string }>;
  idempotencyKey?: string;
}) {
  const apiKey = import.meta.env.ROVELA_API_KEY;
  const from = import.meta.env.ROVELA_FROM;
  const headers: Record<string, string> = {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  };
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;

  const body: Record<string, unknown> = { 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(`${BASE_URL}/emails`, {
    method: 'POST',
    headers,
    body: JSON.stringify(body)
  });

  const payload = await res.json().catch(() => ({}));
  if (!res.ok) {
    throw new ApiError({
      statusCode: payload.statusCode || res.status,
      name: payload.name,
      message: payload.message
    });
  }
  return payload; // { object: 'email', id: '...' }
}

An endpoint that sends after a registration is confirmed

A registration confirmation is a good everyday example for an Astro content site, and it is easy to double-send: the attendee refreshes, a payment webhook retries, an organizer clicks “resend confirmation.” Put the send in an on-demand endpoint, and give every registration a stable Idempotency-Key. 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.

// src/pages/api/registrations/confirm.ts
import type { APIRoute } from 'astro';
import { ApiError, sendEmail } from '../../../lib/emails';

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  const body = await request.json().catch(() => ({}));
  const registrationId = String(body.registrationId || '');
  if (!registrationId) {
    return new Response(JSON.stringify({ message: 'Missing registration' }), { status: 400 });
  }

  const registration = await confirmRegistration(registrationId);
  const ticketUrl = registration.ticketUrl;

  try {
    const result = await sendEmail({
      to: registration.attendeeEmail,
      subject: 'Your event registration is confirmed',
      html: `<p>You are registered.</p><p><a href="${ticketUrl}">View ticket</a></p>`,
      text: `You are registered. View your ticket: ${ticketUrl}`,
      tags: { purpose: 'registration-confirmed', registration_id: registrationId },
      idempotencyKey: `registration-confirmed:${registrationId}`
    });
    return new Response(JSON.stringify({ ok: true, emailId: result.id }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (err) {
    if (err instanceof ApiError) {
      return new Response(
        JSON.stringify({ message: err.message, statusCode: err.statusCode }),
        { status: 502, headers: { 'Content-Type': 'application/json' } }
      );
    }
    throw err;
  }
};

Keep that endpoint off the public internet, or authenticate it yourself — a session cookie, a signed payment callback, or a private network. A static <form> on a conference page should POST to your endpoint, not to api.rovela.dev with a key the HTML can see.

If you later need many personalized messages in one go, 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 module

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 own 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 module you call from every registration endpoint. 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.

Delivery is asynchronous — do not poll from the endpoint

The endpoint 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 request path.

A webhook endpoint in Astro is another on-demand POST route that reads the raw body, 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.

When you need a message to go out later, use scheduled_at (scheduled email). When you need many sends in one request, use batch transactional email. Reusable layouts belong in the Templates API and the templates guide.

A static form-forwarding hack or mailbox SMTP is the wrong default; an on-demand Astro endpoint should use POST /emails

What not to do in an Astro codebase

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 try to send from a pre-rendered page, a client island, or a PUBLIC_ environment variable. Authentication is explicit: anything that ships in HTML is readable. Do not use a generic form-forwarding service as a stand-in for domain email; the From address has to sit on a domain you have verified.

Do not treat this guide as a replacement for the magic-link article. Token issuance, single-use redeem, and keeping click tracking off that link are already covered there. This module is for the mail your event or content site sends after someone already registered — confirmations, reminders, notices.

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

If you send on behalf of several customers 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).

The same module works under any Astro server adapter that can run an on-demand endpoint, because it is just fetch and server-only environment variables. What changes is how the host starts that endpoint. prerender = false is the Astro-specific part; the JSON you post to /emails is not.

A compact Astro checklist

  • Verify the sending domain before you set from. An unverified domain is a 400, not a silent drop.
  • Keep ROVELA_API_KEY in server-only environment variables (never PUBLIC_) and import it only from endpoints or server modules.
  • Set prerender = false on the endpoint, and deploy with a server adapter so the route actually runs.
  • Prefer a sending_access key in production confirmation 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 can hit twice.
  • Record the message id and return from the endpoint. Watch delivery with a webhook, not a loop on the request path.
  • 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 module for the Astro shape.