
Almost every Next.js app needs the same three transactional emails: a welcome email when someone signs up, a password reset link, and a receipt when they pay. This tutorial sends all three from App Router server code with Courier's Node SDK.
Courier sends through the email provider you connect, whether that's Resend, SendGrid, Postmark, or Amazon SES, so you keep the provider and domain you already trust. On top of the send, you get failover to a backup provider, a log for every message, templates your team can edit without a deploy, and SMS or in-app notifications later by changing one routing field.
If you'd rather have Claude Code, Cursor, or Codex do the typing, paste this prompt from your project root:
Add transactional emails (welcome, password reset, receipts) to this Next.js App Router app with Courier.
Follow https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md
Reference app: https://github.com/trycourier/courier-nextjs-email-quickstart
Use @trycourier/courier from a server-only lib/courier.ts and read COURIER_API_KEY from the environment.
Send the welcome email from the signup server action, the password reset from a route handler with one Idempotency-Key per reset, and the receipt from the Stripe webhook with event.id as the key.
Keep my email provider connected in Courier. Never call the provider's API directly.
When done, run npm run send and show me the request id.To skip ahead, clone the finished app: courier-nextjs-email-quickstart.
@trycourier/courier 10.3, and stripe 23.2.Each email is one courier().send.message() call from server code:
| File | What it does |
|---|---|
lib/courier.ts | Creates one server-only Courier client |
scripts/send.ts | Sends a test email from the command line |
app/actions.ts | Sends the welcome email from the signUp server action |
app/api/password-reset/route.ts | Emails a one-time reset link |
app/api/stripe/route.ts | Emails a receipt when a Stripe invoice is paid |
Install the Courier Node SDK, plus server-only to keep your key out of the browser and stripe for the webhook:
npm install @trycourier/courier server-only stripeAdd your keys to .env.local:
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
APP_URL=http://localhost:3000
STRIPE_WEBHOOK_SECRET=whsec_YOUR_STRIPE_WEBHOOK_SECRETUse a Test key while you build, and set DEMO_EMAIL to the address you log in to Courier with. You'll fill in STRIPE_WEBHOOK_SECRET in Step 6.
Every route and server action shares one client:
// lib/courier.ts
import "server-only";
import Courier from "@trycourier/courier";
let client: Courier | undefined;
// Created on first use, so `next build` runs without the key.
export function courier() {
client ??= new Courier({ apiKey: process.env.COURIER_API_KEY });
return client;
}The server-only import makes the build fail if a client component ever imports this file, so the key can't leak to the browser. Nothing sends yet, and next build still passes without a key set.
The SDK retries timeouts and 5xx errors twice by default. Every send in this tutorial carries an idempotency key, so a retry after a request that actually went through never sends a second email.
Before you wire up any forms, check that your key and provider work. Add tsx and dotenv, plus an npm run send script:
npm install --save-dev tsx dotenv
npm pkg set scripts.send="tsx scripts/send.ts"// scripts/send.ts
import { config } from "dotenv";
import Courier from "@trycourier/courier";
// Next.js loads .env.local for you. A standalone script doesn't.
config({ path: ".env.local", quiet: true });
async function main() {
const email = process.env.DEMO_EMAIL;
if (!process.env.COURIER_API_KEY) throw new Error("COURIER_API_KEY is not set in .env.local.");
if (!email || email === "YOUR_EMAIL") throw new Error("DEMO_EMAIL is not set in .env.local.");
// Builds its own client, because `server-only` only resolves inside Next.js.
const client = new Courier({ apiKey: process.env.COURIER_API_KEY });
const { requestId } = await client.send.message({
message: {
to: { user_id: "user_123", email },
routing: { method: "single", channels: ["email"] },
content: {
title: "Welcome to Acme, {{name}}",
body: "Thanks for signing up. Your account is ready.",
},
data: { name: "Sarah Bennett" },
},
});
console.log(`Sent to ${email}. Request id: ${requestId}`);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});Run it:
npm run sendIt prints a request id:
Sent to you@example.com. Request id: 1-67890abc-d1e2f3a4b5c6The email lands in your inbox, and the same request id shows up in Courier Logs with the provider that carried it.
The signUp server action creates the user and sends the welcome email. The account already exists by the time the email goes out, so a failed send gets logged instead of failing the signup:
// app/actions.ts
"use server";
import { randomUUID } from "node:crypto";
import { courier } from "@/lib/courier";
export async function signUp(formData: FormData) {
const name = String(formData.get("name"));
const email = String(formData.get("email"));
// Create the user in your database here. randomUUID() stands in for its id.
const user = { id: randomUUID(), name, email };
try {
await courier().send.message({
message: {
to: { user_id: user.id, email: user.email },
routing: { method: "single", channels: ["email"] },
content: {
title: "Welcome to Acme, {{name}}",
body: "Thanks for signing up. Your account is ready.",
},
data: { name: user.name },
},
// One welcome email per user, even if the SDK retries.
"Idempotency-Key": `welcome-${user.id}`,
});
} catch (error) {
// The account exists either way. Don't fail the signup over the email.
console.error("Welcome email failed", error);
}
}Point a form at it:
// app/page.tsx
import { signUp } from "./actions";
export default function Home() {
return (
<main>
<h1>Create your account</h1>
<form action={signUp}>
<input name="name" placeholder="Name" required />
<input name="email" type="email" placeholder="Email" required />
<button type="submit">Sign up</button>
</form>
</main>
);
}Run npm run dev, open localhost:3000, and sign up with your DEMO_EMAIL. The welcome email arrives with your name in the subject line, and a new row appears in Logs.
A reset email has a security job, so this route builds the link from APP_URL (never the request's Host header). It also sends the email with Next.js's after(), which runs once the response is out. The route answers with the same body, at the same speed, whether or not the account exists, so neither one gives away who has an account.
The send carries an idempotency key. Courier stores the first response for that key for 25 hours, so if the SDK retries the send, the user still gets one email.
// app/api/password-reset/route.ts
import { randomBytes, randomUUID } from "node:crypto";
import { after } from "next/server";
import { courier } from "@/lib/courier";
export async function POST(request: Request) {
// Build reset links from APP_URL, never from the request's Host header.
const appUrl = process.env.APP_URL;
if (!appUrl) throw new Error("APP_URL is not set.");
const { email } = await request.json();
const user = await findUserByEmail(email);
// Same answer either way, so the route can't reveal who has an account.
if (!user) return Response.json({ ok: true });
const resetId = randomUUID();
const token = randomBytes(32).toString("base64url");
// Save resetId, user.id, a hash of the token, and an expiry in your database.
const resetUrl = `${appUrl}/reset-password?token=${token}`;
// Send after the response, so a real account doesn't answer slower than a missing one.
after(() =>
courier().send.message({
message: {
to: { user_id: user.id, email: user.email },
routing: { method: "single", channels: ["email"] },
content: {
version: "2022-01-01",
elements: [
{ type: "meta", title: "Reset your Acme password" },
{ type: "text", content: "Use the button below to choose a new password. The link expires in one hour." },
{ type: "action", content: "Reset password", href: resetUrl },
{ type: "text", content: "If you didn't ask for this, ignore this email." },
],
},
},
// One key per reset, so an SDK retry returns the first response instead of sending a second email.
"Idempotency-Key": `password-reset-${resetId}`,
}),
);
return Response.json({ ok: true });
}
// Replace with your user lookup. This stand-in only knows DEMO_EMAIL.
async function findUserByEmail(email: string) {
return email === process.env.DEMO_EMAIL ? { id: "user_123", email } : null;
}The elements array is Elemental, Courier's content format, which gives you a real button instead of a bare link. Request a reset:
curl -X POST localhost:3000/api/password-reset \
-H "Content-Type: application/json" \
-d '{"email": "YOUR_EMAIL"}'The route answers {"ok":true}, and the reset email arrives with a Reset password button. Because the send runs after the response, a failed send shows up in your server logs and in Courier Logs, not in the curl output.
The webhook route verifies Stripe's signature, then sends the receipt with Stripe's event.id as the idempotency key. Stripe can deliver the same event more than once, and the key stops a second receipt.
// app/api/stripe/route.ts
import Stripe from "stripe";
import { courier } from "@/lib/courier";
// Stripe amounts are in each currency's smallest unit: https://docs.stripe.com/currencies
const ZERO_DECIMAL = new Set(["bif", "clp", "djf", "gnf", "jpy", "kmf", "krw", "mga", "pyg", "rwf", "vnd", "vuv", "xaf", "xof", "xpf"]);
const THREE_DECIMAL = new Set(["bhd", "jod", "kwd", "omr", "tnd"]);
export async function POST(request: Request) {
// Stripe signs the raw body, so read it as text.
const body = await request.text();
const signature = request.headers.get("stripe-signature")!;
let event: Stripe.Event;
try {
event = Stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
} catch {
return new Response("Invalid signature", { status: 400 });
}
if (event.type !== "invoice.payment_succeeded") {
return new Response("Ignored", { status: 200 });
}
const invoice = event.data.object;
if (!invoice.customer_email) return new Response("No email", { status: 200 });
const decimals = ZERO_DECIMAL.has(invoice.currency) ? 0 : THREE_DECIMAL.has(invoice.currency) ? 3 : 2;
const amount = new Intl.NumberFormat("en-US", {
style: "currency",
currency: invoice.currency,
}).format(invoice.amount_paid / 10 ** decimals);
await courier().send.message({
message: {
to: { email: invoice.customer_email },
routing: { method: "single", channels: ["email"] },
content: {
title: `Your Acme receipt for ${amount}`,
body: `We received your payment of ${amount} for invoice ${invoice.number}. Thanks for being a customer.`,
},
},
// Stripe can deliver an event more than once. Its id as the key blocks a second receipt.
"Idempotency-Key": event.id,
});
return new Response("OK", { status: 200 });
}Forward Stripe events to your dev server:
stripe listen --forward-to localhost:3000/api/stripeCopy the whsec_ secret it prints into STRIPE_WEBHOOK_SECRET in .env.local, restart npm run dev, and fire a test event from a second terminal:
stripe trigger invoice.payment_succeeded --override customer:email=YOUR_EMAILThe stripe listen terminal shows your route returning 200, and a receipt with the formatted amount and invoice number arrives. Stripe keeps retrying a webhook for up to three days, longer than Courier's 25-hour key window, so in production also record each event.id you've processed (Courier's Stripe guide covers this).
Inline content works, but every wording change means a deploy. Move the copy into Design Studio and your product or marketing team can edit, preview, and publish it themselves.
{{data.name}} for the name: Design Studio variables need the data. prefix.welcome-email, and select Publish.Then send by alias instead of passing content:
// app/actions.ts
"use server";
import { randomUUID } from "node:crypto";
import { courier } from "@/lib/courier";
export async function signUp(formData: FormData) {
const name = String(formData.get("name"));
const email = String(formData.get("email"));
// Create the user in your database here. randomUUID() stands in for its id.
const user = { id: randomUUID(), name, email };
try {
await courier().send.message({
message: {
to: { user_id: user.id, email: user.email },
// The template's alias. Its copy, design, and routing live in Courier.
template: "welcome-email",
data: { name: user.name },
},
"Idempotency-Key": `welcome-${user.id}`,
});
} catch (error) {
console.error("Welcome email failed", error);
}
}Sign up again and you get the Design Studio version. Sends always render the published version, so a half-finished edit never reaches a user, and each message's log records which version it used. Do the same for password-reset and receipt, passing resetUrl and amount in data.
Courier adds three things a plain email API doesn't:
routing. This line sends to both email and the in-app Courier Inbox:routing: { method: "all", channels: ["email", "inbox"] },Use method: "single" with ["email", "sms"] to send an SMS only when email can't go out, once the user's profile has a phone_number.
401 on every sendThe API key is missing or wrong. Copy it again from API Keys, and check that .env.local has no quotes or spaces around it.
UNROUTABLE or NO_PROVIDERS in LogsThe key's environment has no email provider. Connect one in the same environment as your key (Test and Production each have their own integrations).
The Test environment's built-in provider only delivers to teammates in your workspace. Send to your Courier login address, or connect your own provider to the Test environment.
UNMAPPED after switching to a templateCourier couldn't find a template with that alias. Check that the alias in the template's settings matches the template value in your code exactly.
You now send welcome, password reset, and receipt emails from Next.js server code with one SDK call each:
lib/courier.ts keeps the key off the browser.When you're ready for production, Go live covers switching to a Production key and connecting your provider there. To bring an existing Resend, SendGrid, Postmark, or SES setup across without DNS changes, see Keep your email provider and add Courier.
Yes. Connect the Resend integration in Courier, and every email goes out through your Resend account and verified domain. The same goes for SendGrid, Postmark, Amazon SES, and the other email providers Courier supports.
Yes. A server action runs on the server, so it can call client.send.message(). Import the client from a module marked import "server-only" so the API key never reaches the browser.
Pass an Idempotency-Key with the send, unique per reset. When the SDK retries the send, the same key gets the first response back for 25 hours instead of sending another email. A second form submit is a new reset with a new key, so return early if the user already has an unexpired one.
No. You can pass content inline, as Steps 4 to 6 do. Templates make sense once someone other than you needs to change the wording.

Office 365 SMTP settings after basic auth ends
The Office 365 SMTP settings are smtp.office365.com, port 587, and STARTTLS with a mailbox username and password. At the end of December 2026, Microsoft turns off Basic auth for SMTP AUTH by default, and app passwords stop working with it. Here's how to check what you have, and which option fits a scanner, an internal app, or a product that emails customers.

FCM changes for 2027: what to migrate and when
Google is retiring FCM device groups and the InstanceId server APIs on September 29, 2027, and new projects lose access on January 1, 2027. Most senders on the HTTP v1 API aren't affected. Here's how to check your code, replace device groups with your own per-user token list, move topic management and token validation to the v1 APIs, and what the move from registration tokens to Firebase installation IDs means for you.

Is Courier HIPAA compliant? BAAs, SOC 2, and controls
Yes, Courier maintains a HIPAA compliance program and signs BAAs with Enterprise customers. Here's what Courier runs, from SOC 2 Type II to continuous security monitoring, what the BAA covers, the controls you get, and the parts of HIPAA compliance that stay with you.