Blog

Add transactional email to a Next.js app

Thomas SchiavoneThomas Schiavone
Next.js transactional email cover

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.

Hand this to your coding agent

If you'd rather have Claude Code, Cursor, or Codex do the typing, paste this prompt from your project root:

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

Prerequisites

  • A Next.js app on the App Router. The code here is written against Next.js 16.4, @trycourier/courier 10.3, and stripe 23.2.
  • Node.js 20.9 or newer
  • A Courier account and an API key
  • An email provider connected in Courier, such as Resend. A new workspace's Test environment already has a testing provider that delivers to you and your teammates, so you can start without one.
  • The Stripe CLI, for the receipt step

What you'll build

Each email is one courier().send.message() call from server code:

FileWhat it does
lib/courier.tsCreates one server-only Courier client
scripts/send.tsSends a test email from the command line
app/actions.tsSends the welcome email from the signUp server action
app/api/password-reset/route.tsEmails a one-time reset link
app/api/stripe/route.tsEmails a receipt when a Stripe invoice is paid

Step 1: Install the SDK and add your keys

Install the Courier Node SDK, plus server-only to keep your key out of the browser and stripe for the webhook:

Terminal
npm install @trycourier/courier server-only stripe

Add your keys to .env.local:

Terminal
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
APP_URL=http://localhost:3000
STRIPE_WEBHOOK_SECRET=whsec_YOUR_STRIPE_WEBHOOK_SECRET

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

Step 2: Create a server-only Courier client

Every route and server action shares one client:

TypeScript
// 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.

Step 3: Send a test email from the command line

Before you wire up any forms, check that your key and provider work. Add tsx and dotenv, plus an npm run send script:

Terminal
npm install --save-dev tsx dotenv
npm pkg set scripts.send="tsx scripts/send.ts"
TypeScript
// 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:

Terminal
npm run send

It prints a request id:

Terminal
Sent to you@example.com. Request id: 1-67890abc-d1e2f3a4b5c6

The email lands in your inbox, and the same request id shows up in Courier Logs with the provider that carried it.

Step 4: Send the welcome email from a server action

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:

TypeScript
// 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:

TSX
// 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.

Step 5: Send the password reset from a route handler

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.

TypeScript
// 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:

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

Step 6: Send a receipt from the Stripe webhook

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.

TypeScript
// 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:

Terminal
stripe listen --forward-to localhost:3000/api/stripe

Copy 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:

Terminal
stripe trigger invoice.payment_succeeded --override customer:email=YOUR_EMAIL

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

Step 7: Move the copy into templates

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.

  1. In Courier, open Templates, select Add template, and build the welcome email. Use {{data.name}} for the name: Design Studio variables need the data. prefix.
  2. Open the template's settings (the gear icon), set its Alias to welcome-email, and select Publish.

Then send by alias instead of passing content:

TypeScript
// 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.

Add failover, SMS, and in-app without rewriting the send

Courier adds three things a plain email API doesn't:

  • Provider failover. Connect a second email provider, say SendGrid or Postmark next to Resend, and Courier moves to the next provider when one errors. Every attempt shows in the message's log.
  • One log per message. Logs show who got each email, which provider carried it, the rendered content, and why it failed if it did. Your agent can read the same records through the Courier MCP server.
  • More channels on the same call. Adding a channel is a change to routing. This line sends to both email and the in-app Courier Inbox:
TypeScript
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.

Troubleshooting

401 on every send

The 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 Logs

The 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 email never arrives on a Test key

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 template

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

Wrapping up

You now send welcome, password reset, and receipt emails from Next.js server code with one SDK call each:

  • One server-only client in lib/courier.ts keeps the key off the browser.
  • Idempotency keys on every send stop duplicate emails on retries.
  • Templates move the copy out of your codebase, so wording changes skip the deploy.
  • Your email provider stays yours, with failover, logs, and new channels on top.

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.

Frequently asked questions

Can I keep using Resend with 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.

Can I send email from a Next.js server action?

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.

How do I stop a password reset email from sending twice?

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.

Do I need a template to send email with Courier?

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.