Next.js direct mail: send postcards from server code
Next.js direct mail is one fetch from server code: a Server Action, a Route Handler or an after() callback posts the address to Mailr with a key that never reaches the browser, and Mailr prints and mails the postcard.
What to mail from Next.js
| When this happens | Mail this |
|---|---|
| A Server Action places a customer's first order | A thank-you postcard, sent in after() so checkout doesn't wait on it. (First-order thank you) |
| Your scheduler calls a Route Handler once a day | Win-back postcards to everyone 60+ days past their last order, one batch per 1,000. (Win-back) |
| Your Stripe webhook route gets the final invoice.payment_failed | A plain billing letter after the emails didn't work. (Failed payment) |
Set it up
- Put the key on the server. Add MAILR_API_KEY=mlr_test_... to .env.local in the project root (not in /src). Without a NEXT_PUBLIC_ prefix, Next.js only exposes it to server code. In production, set it in your host's environment settings.
- Add one helper. lib/mailr.ts below imports server-only, so the build fails if a Client Component ever imports it, and sends every request with an Idempotency-Key.
- Call it where the event happens. In a Server Action, wrap the call in after() so the user gets their response without waiting on the postcard request (after() is stable since Next.js 15.1). In a Route Handler, call it directly.
- Save the id, test, go live. Store the returned id on the order or customer and skip records that already have one. Test pieces reach processed_for_delivery in about 8 minutes; then add funds and swap in the live key.
Next.js code
import "server-only";
export type Address = { name: string; line1: string; line2?: string; city: string; state: string; zip: string };
// Your return address. Mailr prints it in the address block.
export const FROM: Address = { name: "Acme Outdoor", line1: "1 Example Way", city: "Phoenix", state: "AZ", zip: "85004" };
/** POST to Mailr. The same Idempotency-Key within 24 hours returns the first response instead of mailing twice. */
export async function mailr<T = { id: string; status: string }>(path: string, body: object, idempotencyKey: string): Promise<T> {
const res = await fetch(`https://api.mailr.dev/v1${path}`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MAILR_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) throw new Error(`Mailr ${res.status}: ${data.error?.message}`);
return data as T;
}- Server Actions can be called with a direct POST, not only from your form. Check the session inside every action that can mail something, as placeOrder does.
- after() runs within your route's max duration. On serverless hosts it needs waitUntil support (Vercel has it), and it doesn't run in a static export.
- Vercel Cron Jobs send CRON_SECRET as a Bearer token, don't retry a failed run, and can occasionally deliver the same run twice. The key built from the batch's customer ids makes a double run harmless.
- Merge values have length caps (first_name 14 characters, last_product 22). A longer value fails with a 422 before anything prints, so trim or fall back first.
What it costs
Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.
Templates that fit: First-order thank you (6x9), Win-back (6x11), Failed payment (8.5x11).
Questions
Can I call Mailr from a Client Component?
No. Mailr keys are secret, and a key in client code ships to every visitor's browser. Call a Server Action or a Route Handler, which reads MAILR_API_KEY on the server.
Do I need an SDK?
No, and there isn't an official one yet. The helper above is the whole client: fetch, a Bearer key and an Idempotency-Key.
How do I know when a postcard was delivered?
Mailr has no webhooks yet. Read GET /v1/postcards/{id} when you need the status, for example on an admin page. Its events list every step with a time.