TanStack Start Transactional Email API (2026): Send App Mail from a Server Function with POST /emails
Send transactional email from TanStack Start with Rovela’s HTTP API: a server-only module, a createServerFn after an export is ready, environment variables for the Bearer key, and Idempotency-Key. Not a Next.js or Remix rewrite.
TanStack Start already has server functions; transactional email belongs there
A TanStack Start app already splits the tree in two: components render in the browser, and server functions — createServerFn, modules that never leave the server bundle — do anything that needs a secret. Transactional email — “your export is ready,” a billing notice, a security alert — is that second kind of work. The natural way to send it is one HTTPS POST with a Bearer key, not an SMTP session that accidentally ships into the client graph.
Rovela’s Email API is built for that. There is no client library to install and no official TanStack plugin you have to pin. 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 Next.js rewrite and it is not a Remix rewrite. Next.js already has sending email from Next.js; Remix’s everyday-send shape lives in the Remix transactional email guide. TanStack Start’s difference is the server function: a createServerFn that runs only on the server, a module the client router cannot import, and an export-ready notice that is not a magic link. If you need a sign-in link, use the existing magic-link articles for those frameworks and keep this utility for mail you send after a user already asked for a file.
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 TanStack Start server function belongs on POST /emails.
What you need before the first TanStack Start send
The first-email guide and the Quick Start are the same five steps, whether your caller is curl or fetch inside a server function:
- Create an account. You start on the free plan, which sends real mail. There is no separate sandbox or test key.
- Add and verify a sending domain (a subdomain such as
mail.example.comis a common choice). You cannot send from a domain you have not verified; an unverified or foreignfromis refused with a 400 that names the domain. See the domain setup guide and what domain email is. - Create an API key. A
sending_accesskey can send and nothing else — the right default for production. Afull_accesskey can also read messages and events, and manage domains, templates, and webhooks. The full key is shown once. - Send with
POST /emails. - Confirm delivery in the dashboard, with
GET /emails/:idorGET /emails/:id/events(those reads needfull_accessor 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 server-only emails module and environment variables
Keep the key on the server. Never prefix it for a public Vite env (VITE_), never import the module from a component that also runs in the browser, and never return the key from a loader. A leaked sending_access key can send mail as your domain.
In TanStack Start, private values belong in the server environment — process.env on Node, or the equivalent server bindings of your host — and are read only from a module that the client bundle cannot reach. A .server.ts suffix, or a file imported solely by createServerFn handlers, is the usual guard.
# .env (server only; never VITE_*)
ROVELA_API_KEY=re_your_sending_key
ROVELA_FROM=Acme <hello@mail.example.com>
The helper below uses the platform fetch already available in the server 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.
// src/lib/emails.server.ts
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 = process.env.ROVELA_API_KEY
const from = process.env.ROVELA_FROM
if (!apiKey || !from) {
throw new Error('Missing ROVELA_API_KEY or 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('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 as { object: string; id: string }
}
Do not import emails.server.ts from a route component. Import it only from a server function. That is the difference between “the key lives in env” and “the key also lives in the JavaScript the browser downloaded.”
A server function that sends after an export is ready
A finished data export is a good everyday example because it is not a login link and it is easy to double-send: a worker retries, the user clicks “email me the file” twice, a dev tools replay hits the function again. Put the send behind createServerFn, and give every export 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.
The import path below follows the common React binding for TanStack Start. The idea is the same if your project’s package name differs slightly: the function must be declared as a server function, and the emails module must stay server-only.
// src/functions/notify-export-ready.ts
import { createServerFn } from '@tanstack/react-start'
import { sendEmail, ApiError } from '../lib/emails.server'
export const notifyExportReady = createServerFn({ method: 'POST' })
.validator((data: { exportId: string }) => {
if (!data?.exportId) {
throw new Error('Missing export')
}
return data
})
.handler(async ({ data }) => {
const exp = await loadReadyExport(data.exportId)
const downloadUrl = signedExportUrl(exp)
try {
const result = await sendEmail({
to: exp.ownerEmail,
subject: 'Your export is ready',
html: `<p>Your export can be downloaded here:</p><p><a href="${downloadUrl}">Download export</a></p>`,
text: `Your export can be downloaded: ${downloadUrl}`,
tags: { purpose: 'export-ready', export_id: data.exportId },
idempotencyKey: `export-ready:${data.exportId}`,
})
return { ok: true, emailId: result.id }
} catch (err) {
if (err instanceof ApiError) {
throw new Error(`Rovela ${err.statusCode}: ${err.message}`)
}
throw err
}
})
Call notifyExportReady from a component only after the user is authenticated, the same way you would call any other mutation. The browser posts to your server function, not to api.rovela.dev. The function is the only place that reads ROVELA_API_KEY.
loadReadyExport and signedExportUrl are your domain code. This article does not invent a Rovela export endpoint — Rovela accepts the message you already decided to send.
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, afromdomain that does not belong to your organization, atemplatethat does not exist, or more than 50 recipients on one message.401— missing or invalid credential, or asending_accesskey 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 onRetry-Afterwhen 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 export job. 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 server function
The function 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 TanStack Start is a server 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). 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.
What not to do in a TanStack Start 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 put a Rovela key in VITE_ variables, a module imported by a route component, or a public repository. Call the API from createServerFn or another server-only module. Authentication is explicit: a browser bundle is readable by anyone who has it.
Do not treat this guide as a magic-link article. Token generation, expiry, and one-time consumption are a different design. This function is for mail your product sends after a user already has a session — finished exports, notices, receipts.
Hosted mailboxes are a different product surface. People can read and send from them in a mail app. Your TanStack Start server should not share a device credential with someone else’s Apple Mail 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 helper is just fetch and server env, so it works on a Node host or another server runtime Start can target. What must not change is the boundary: the client router never sees the key. If you also have API routes, keep them for webhooks and machine-to-machine calls — they are a poor place to open an SMTP connection, and an easy place to import a server module into a file that later ships to the browser.
This is also not a drop-in replacement for the Next.js or Remix posts. Those frameworks already have their own everyday-send shapes. Start’s difference is createServerFn plus a server-only module, used here for an export-ready notice rather than a login email.
A compact TanStack Start checklist
- Verify the sending domain before you set
from. An unverified domain is a 400, not a silent drop. - Keep
ROVELAcredentials in server env and import them only from server-only modules. - Prefer a
sending_accesskey in production export jobs; keepfull_accessfor tooling that reads events or manages webhooks. - Send both
htmlandtextwhen you can, and set anIdempotency-Keyon any path a retry can hit twice. - Record the message
idand return from the server function. 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 TanStack Start shape.