> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Adding notifications to a framework app? Start from its quickstart, which has a runnable repo and complete files: Next.js email https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md, Django https://www.courier.com/docs/guides/add-notifications-to-django.md, Rails https://www.courier.com/docs/guides/add-notifications-to-rails.md, Node.js digest https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md, and the React, Next.js, and Astro inbox quickstarts under /guides/add-an-inbox-to-*.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Add transactional emails to a Next.js app

> Send welcome, password reset, and Stripe receipt emails from a Next.js App Router app with Courier, delivered through Resend or any provider you connect.

Add welcome, password reset, and receipt emails to a Next.js App Router app by calling Courier's `client.send.message` from server code. Courier delivers them through Resend and adds SMS, push, and in-app when you need them.

```ts theme={null}
import Courier from "@trycourier/courier";

// Reads COURIER_API_KEY from the environment.
const client = new Courier();

const { requestId } = await client.send.message({
  message: {
    to: { email: process.env.DEMO_EMAIL },
    routing: { method: "single", channels: ["email"] },
    content: { title: "Welcome to Acme", body: "Your account is ready." },
  },
});

console.log(`Sent. Request id: ${requestId}`);
```

Save it as `first-send.mts`, then run it with your API key and email address:

```bash theme={null}
npm install @trycourier/courier && COURIER_API_KEY=YOUR_COURIER_API_KEY DEMO_EMAIL=YOUR_EMAIL npx --yes tsx first-send.mts
```

It prints a request id that you'll find in [Courier Logs](https://app.courier.com/logs). On a Test key, use your Courier login address. [Test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches it with no provider connected.

> [card] [courier-nextjs-email-quickstart](https://github.com/trycourier/courier-nextjs-email-quickstart)
>
> The finished Next.js app from this guide, ready to clone and run.

## Build this with a coding agent

To have a coding agent add Courier to your Next.js app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
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 and the reference app at 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 Resend as the email provider, connected in Courier.
When done, run npm run send and show me the request id.
```

Install the Courier skill with `npx skills add trycourier/courier-skills`, and connect the [Courier MCP server](https://www.courier.com/docs/resources/mcp.md) so the agent can check Courier Logs and templates itself.

### Rules for AI agents

* Use `@trycourier/courier` through `lib/courier.ts`, which keeps `import "server-only"`. Only the standalone `scripts/send.ts` builds its own client.
* Read `COURIER_API_KEY` from the environment on the server. Never import the client into a client component.
* Pass an `"Idempotency-Key"` on resets and receipts: `password-reset-${resetId}` for a reset, Stripe's `event.id` for a receipt.
* Send from the server action or route handler that owns the event. Verify the Stripe signature before sending a receipt.
* Build reset links from `APP_URL`, never from the request's `Host` header.
* Never call Resend directly. Courier routes the `email` channel to it.

## What you'll build

This Next.js 16 App Router app sends three emails, each one `client.send.message` call from [`@trycourier/courier`](https://www.courier.com/docs/sdk-libraries/node):

* **A welcome email** from the `signUp` server action
* **A password reset email** from `POST /api/password-reset`
* **A receipt email** from `POST /api/stripe`, on `invoice.payment_succeeded`

## Prerequisites

### For the first send

* [A Courier API key](https://app.courier.com/settings/api-keys)
* Node.js 20.9 or newer

### For the full build

* A Next.js app on the App Router
* [A Resend integration connected in Courier](https://www.courier.com/docs/integrations/email/resend.md)
* [A verified sending domain in Resend](https://resend.com/domains)
* [The Stripe CLI](https://docs.stripe.com/stripe-cli)

## Clone the finished Next.js app

Clone the Courier Next.js quickstart to run the finished app with your own key:

```bash theme={null}
git clone https://github.com/trycourier/courier-nextjs-email-quickstart.git
cd courier-nextjs-email-quickstart
npm install
cp .env.example .env.local   # add COURIER_API_KEY and DEMO_EMAIL
npm run send
```

The steps below add or change these files:

| File | What it does |
| :- | :- |
| `lib/courier.ts` | The server-only Courier client |
| `app/actions.ts` | Sends the welcome email on signup |
| `app/page.tsx` | The signup form |
| `app/api/password-reset/route.ts` | Emails a one-time reset link |
| `app/api/stripe/route.ts` | Emails a receipt for a paid invoice |
| `scripts/send.ts` | Sends a test welcome email |

## Install the Courier Node SDK in your Next.js app

Install the Courier Node SDK, `@trycourier/courier`, in your Next.js app with `server-only` and `stripe`:

```bash theme={null}
npm install @trycourier/courier server-only stripe
```

Add your keys to `.env.local`, as in the repo's [`.env.example`](https://github.com/trycourier/courier-nextjs-email-quickstart/blob/main/.env.example):

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
APP_URL=http://localhost:3000
STRIPE_WEBHOOK_SECRET=whsec_YOUR_STRIPE_WEBHOOK_SECRET
```

## Create a server-only Courier client for Next.js

`lib/courier.ts` gives every Next.js route one Courier client that stays on the server.

```ts lib/courier.ts theme={null}
import "server-only";
import Courier from "@trycourier/courier";

let client: Courier | undefined;

// One client for the whole app, created on first use so `next build` runs
// without the key. `server-only` fails the build if a client component
// imports this file, which keeps your API key out of the browser.
export function courier() {
  client ??= new Courier({ apiKey: process.env.COURIER_API_KEY });
  return client;
}
```

## Send a welcome email from a Next.js server action

The Next.js `signUp` server action sends the welcome email through Courier.

```ts app/actions.ts theme={null}
"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 and use its id. randomUUID() stands in
  // for that id here, so each signup gets its own Courier profile.
  const user = { id: randomUUID(), name, email };

  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 },
    },
  });
}
```

Post a form to it from a page:

```tsx app/page.tsx theme={null}
import { signUp } from "./actions";

export default function Home() {
  return (
    <main>
      <h1>Create your account</h1>
      <form action={signUp} style={{ display: "grid", gap: "0.75rem" }}>
        <input name="name" placeholder="Name" required />
        <input name="email" type="email" placeholder="Email" required />
        <button type="submit">Sign up</button>
      </form>
    </main>
  );
}
```

## Send a password reset email from a Next.js route handler

The Next.js route handler emails a one-time reset link through Courier, with one [idempotency key](https://www.courier.com/docs/reference/api-overview.md#idempotency) per reset.

```ts app/api/password-reset/route.ts theme={null}
import { randomBytes, randomUUID } from "node:crypto";
import { courier } from "@/lib/courier";

export async function POST(request: Request) {
  // Build reset links from your configured URL, never from the request's Host
  // header. Check it first, so a missing value fails the same way for everyone.
  const appUrl = process.env.APP_URL;
  if (!appUrl) throw new Error("APP_URL is not set. Reset links need your app's public URL.");

  const { email } = await request.json();
  const user = await findUserByEmail(email);

  // Answer the same way whether or not the account exists, so this route
  // can't be used to find out who has one.
  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}`;

  await 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. If the SDK retries this call, Courier returns the
    // first response instead of sending a second email.
    "Idempotency-Key": `password-reset-${resetId}`,
  });

  return Response.json({ ok: true });
}

// Stand-in for your user lookup. Replace it with a query against your database.
// It only knows the demo user, so this route can't email arbitrary addresses.
async function findUserByEmail(email: string) {
  return email === process.env.DEMO_EMAIL ? { id: "user_123", email } : null;
}
```

## Send a receipt email from a Stripe webhook in Next.js

The Next.js Stripe webhook route verifies the event, then sends a receipt through Courier keyed by the event id.

```ts app/api/stripe/route.ts theme={null}
import Stripe from "stripe";
import { courier } from "@/lib/courier";

// Stripe sends amounts in each currency's smallest unit. Most use two decimal
// places; these use none or three. 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, not JSON.
  const body = await request.text();
  const signature = request.headers.get("stripe-signature")!;

  let event: Stripe.Event;
  try {
    // Verifying a signature needs only the signing secret, not a Stripe API key.
    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 the same event more than once. The event id as the
    // key means a repeat delivery can't send a second receipt.
    "Idempotency-Key": event.id,
  });

  return new Response("OK", { status: 200 });
}
```

## Add a test send script

`scripts/send.ts` sends the welcome email from the command line, so you can check your key and Resend before wiring up a form. `server-only` resolves only inside Next.js, so the script builds its own client. Add its tools and an `npm run send` script:

```bash theme={null}
npm install --save-dev tsx dotenv
npm pkg set scripts.send="tsx scripts/send.ts"
```

```ts scripts/send.ts theme={null}
import { config } from "dotenv";
import Courier from "@trycourier/courier";

// Next reads .env.local automatically. A standalone script does not.
config({ path: ".env.local", quiet: true });
config({ quiet: true });

/**
 * Sends the welcome email from app/actions.ts to DEMO_EMAIL, so you can prove
 * your API key and your Resend integration work before you wire up a form.
 */
async function main() {
  const apiKey = process.env.COURIER_API_KEY;
  const email = process.env.DEMO_EMAIL;

  if (!apiKey) {
    console.error("COURIER_API_KEY is not set. Add it to .env.local.");
    process.exit(1);
  }

  if (!email || email === "YOUR_EMAIL") {
    console.error("DEMO_EMAIL is not set. Put your own email address in .env.local.");
    process.exit(1);
  }

  const client = new Courier({ apiKey });

  const { requestId } = await client.send.message({
    message: {
      // A demo user. Your app sends to the signed-up user from its database.
      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}`);
  console.log("Open https://app.courier.com/logs to follow it to Resend.");
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
```

## Verify

Send each Next.js email once, then find it in [Courier Logs](https://app.courier.com/logs):

1. Run `npm run send`. It prints a request id.
2. Run `npm run dev`, open `localhost:3000`, and sign up with your email.
3. Request a reset for your `DEMO_EMAIL` address. The route answers `{"ok":true}` either way, so check Logs: `curl -X POST localhost:3000/api/password-reset -H "Content-Type: application/json" -d '{"email": "YOUR_DEMO_EMAIL"}'`
4. Run `stripe listen --forward-to localhost:3000/api/stripe`, put its `whsec_` secret in `.env.local`, restart, then `stripe trigger invoice.payment_succeeded --override customer:email=YOUR_EMAIL`

| What you see | Fix |
| :- | :- |
| `401` | Copy the key from [Platform → API Keys](https://app.courier.com/settings/api-keys) |
| `UNROUTABLE`, `NO_PROVIDERS` | Connect Resend in your key's environment |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. In a Next.js app it sends through Resend. [Go live](https://www.courier.com/docs/guides/go-live.md) covers moving from Test to Production:

* **Use a Production key**, with Resend connected in Production.
* **Record processed Stripe event ids.** Stripe retries for three days, past Courier's 25-hour idempotency window ([Stripe guide](https://www.courier.com/docs/guides/notify-from-stripe.md#make-it-reliable)).
* **Put resets and receipts on a `REQUIRED` topic** so [preferences](https://www.courier.com/docs/recipients/preferences/overview.md) never block them.

| Task | Calling Resend directly | With Courier |
| :- | :- | :- |
| Add SMS, push, or in-app | A new SDK per channel | Add it to `routing` |
| Provider failover | Your own logic | [Failover](https://www.courier.com/docs/send/routing.md#failover) |
| Opt-outs | Your own table | [Preferences](https://www.courier.com/docs/recipients/preferences/overview.md) |
| Tracing | One log per provider | One [log](https://www.courier.com/docs/monitor/logs.md) |

## FAQ

> [accordion] Can I keep using Resend with Courier?
>
> Resend stays your email provider when you add Courier. Connect the [Resend integration](https://www.courier.com/docs/integrations/email/resend.md), and Courier sends every email through it.

> [accordion] How do I stop a password reset email from sending twice?
>
> A password reset sends once per `"Idempotency-Key"`, which covers retries for 25 hours. A second form submit is a new reset, so return early when the user has an unexpired one.

> [accordion] Can I send email from a Next.js server action?
>
> A Next.js server action runs on the server, so it can call Courier's `client.send.message` from a module marked `import "server-only"`.

> [accordion] How do I add SMS or in-app notifications later?
>
> Courier adds a channel through the send's `routing`. Connect an SMS provider or the [Courier Inbox](https://www.courier.com/docs/in-app/overview.md), then list it: `method: "single"` falls back in order, and `method: "all"` sends on every channel.
