> ## 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, Laravel https://www.courier.com/docs/guides/add-notifications-to-laravel.md, FastAPI https://www.courier.com/docs/guides/send-notifications-from-fastapi.md, Express https://www.courier.com/docs/guides/add-notifications-to-express.md, and the React, Next.js, Astro, and Nuxt 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 notifications to an Express app

> Send email, SMS, and in-app notifications from an Express app with Courier: one route, one send, an inbox page, and the email and SMS providers you use.

Send email, SMS, and in-app notifications from an Express app with one Courier call in a route, and show the in-app message in a `<courier-inbox>`.

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

const email = process.env.DEMO_EMAIL;
if (!email) throw new Error("Set DEMO_EMAIL to your own email address.");
const client = new Courier(); // Reads COURIER_API_KEY from the environment.

const { requestId } = await client.send.message({
  message: {
    to: { email },
    routing: { method: "single", channels: ["email"] },
    content: { title: "Hello from Express", body: "Your Express app can send notifications." },
  },
});

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

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

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

On a Test key, use your Courier login email, which [Test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches with no provider. Look up the request id in [Courier Logs](https://app.courier.com/logs).

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

## Build this with a coding agent

Paste this prompt into Claude Code, Cursor, or Codex from your Express project root to have a coding agent add Courier:

```text theme={null}
Add email, SMS, and in-app notifications to this Express app with Courier.
Follow https://www.courier.com/docs/guides/add-notifications-to-express.md and the reference app at https://github.com/trycourier/courier-express-quickstart.
Use @trycourier/courier and read COURIER_API_KEY from the environment, on the server only.
Send all three channels in one client.send.message with routing method "all", after the event's transaction commits, with one Idempotency-Key per event, and skip SMS when the user has no phone.
Add GET /courier/token that mints the inbox JWT for the session user, never a user id from the request, and render <courier-inbox> on a page.
When done, add a send command like the reference app's npm run send (scripts/send.ts), run it, 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 Logs itself.

### Rules for AI agents

* Call `@trycourier/courier` through `lib/courier.ts`, not raw HTTP, and keep `COURIER_API_KEY` on the server.
* Send all channels in one `client.send.message` with routing `"all"`, dropping `sms` without a `phone_number`.
* Send after the transaction commits, keyed `task-assigned-${assignmentId}`, and [retry safely](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).
* Mint the inbox JWT for `res.locals.user`, never a request's user id, and answer 401 without one.
* Build links from `APP_URL`, never the `Host` header, and never call providers directly.

## What you'll build

This Express 5 app uses Courier to notify a teammate who gets a task:

* **An email, a text, and an in-app message** from one send in `POST /tasks/:taskId/assign`
* **A `GET /courier/token` route** that signs the session user in to the inbox
* **A static `<courier-inbox>` page** with no bundler

Tested in November 2026 with Express 5.3, `@trycourier/courier` 10.2.0, and Node.js 22.18.

## Prerequisites

### For the first send

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

### For the full build

* An Express 5 app
* [An SMS provider, such as Twilio](https://www.courier.com/docs/integrations/sms/twilio.md)

## Clone the finished Express app

Clone the Courier Express quickstart and run it with your own key:

```bash theme={null}
git clone https://github.com/trycourier/courier-express-quickstart.git
cd courier-express-quickstart
npm install
cp .env.example .env   # add your key and DEMO_EMAIL
npm run dev
```

The steps below build these files:

| File | What it does |
| - | - |
| `package.json` | ES modules and scripts that load `.env` |
| `.env` | Your key, `APP_URL`, and demo user |
| `lib/courier.ts` | The client and `notifyTaskAssigned` |
| `server.ts` | The assign and token routes |
| `public/index.html` | Renders `<courier-inbox>` |

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

Install the Courier Node.js SDK, [`@trycourier/courier`](https://www.courier.com/docs/sdk-libraries/node), with Express and `tsx`, which runs TypeScript:

```bash theme={null}
npm install @trycourier/courier express
npm install -D tsx typescript @types/express @types/node
```

Set `"type": "module"` in [`package.json`](https://github.com/trycourier/courier-express-quickstart/blob/main/package.json) and add scripts that load `.env` with `tsx --env-file`:

> [accordion] package.json (additions)
>
> ```json theme={null}
> "type": "module",
> "scripts": {
>   "dev": "tsx watch --env-file=.env server.ts",
>   "start": "tsx --env-file=.env server.ts"
> }
> ```

In a CommonJS app, keep its `type` and rename `server.ts`, `lib/courier.ts`, and top-level-`await` scripts to `.mts`, then import `./lib/courier.mts` and point the scripts and any `tsconfig.json` `include` at `server.mts`.

Then create `.env`:

```bash .env theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
# Notification links start with this URL.
APP_URL=http://localhost:3000
# DEMO ONLY: every request acts as user_123. Unset it in production.
DEMO_EMAIL=YOUR_EMAIL
# Optional, in E.164. Leave it empty to skip SMS.
DEMO_PHONE=
```

## Send email, SMS, and in-app notifications from Express

In the Express app, `notifyTaskAssigned` makes one Courier call to [`POST /send`](https://www.courier.com/docs/api-reference/send/send-a-message) that reaches email, SMS, and the inbox.

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

// Fail at startup, not mid-request, when the key is missing.
const apiKey = process.env.COURIER_API_KEY;
if (!apiKey) {
  throw new Error("COURIER_API_KEY is not set. Add it to .env.");
}

export const courier = new Courier({ apiKey });

export type User = {
  id: string;
  email?: string;
  phone_number?: string;
};

export type Task = {
  id: string;
  title: string;
  url: string;
};

// Call once per assignment, after it's saved.
export async function notifyTaskAssigned(assignee: User, task: Task, assignmentId: string) {
  // Text only teammates with a phone number.
  const channels = assignee.phone_number ? ["email", "sms", "inbox"] : ["email", "inbox"];

  const { requestId } = await courier.send.message(
    {
      message: {
        // user_id picks the inbox, so it must match the token's user.
        to: { user_id: assignee.id, email: assignee.email, phone_number: assignee.phone_number },
        content: {
          title: `New task: ${task.title}`,
          body: `You're assigned to it. Open it here: ${task.url}`,
        },
        // "all" sends on every listed channel, not just the first that works.
        routing: { method: "all", channels },
      },
      // One key per assignment, so a retry sends at most once.
      "Idempotency-Key": `task-assigned-${assignmentId}`,
    },
    // Fail fast: SDK retries would wait out Retry-After inside the request.
    { maxRetries: 0 },
  );

  return requestId;
}
```

`{ maxRetries: 0 }` fails a 429 or 409 fast instead of holding the request open, so [retry from a queue](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).

## Send from an Express route and mint the inbox token

The Express assign route calls Courier through `notifyTaskAssigned` after saving the assignment. The token route mints a one-user JWT with [`POST /auth/issue-token`](https://www.courier.com/docs/api-reference/authentication/create-a-jwt).

```ts server.ts lines theme={null}
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import express, { type NextFunction, type Request, type Response } from "express";
import { APIConnectionError, ConflictError, RateLimitError } from "@trycourier/courier";
import { courier, notifyTaskAssigned, type User } from "./lib/courier.ts";

// Build links from APP_URL, never the request's Host header.
const appUrl = process.env.APP_URL;
if (!appUrl) throw new Error("APP_URL is not set. Links in notifications need your app's public URL.");

const demoEmail = process.env.DEMO_EMAIL;
if (demoEmail === "YOUR_EMAIL") throw new Error("Set DEMO_EMAIL in .env to your own email address.");

// DEMO ONLY. While DEMO_EMAIL is set, every request acts as user_123.
const demoUser: User | undefined = demoEmail
  ? { id: "user_123", email: demoEmail, phone_number: process.env.DEMO_PHONE || undefined }
  : undefined;

// Your auth middleware puts the signed-in user in res.locals.user.
function sessionUser(res: Response): User | undefined {
  return res.locals.user ?? demoUser;
}

function findTeammate(id: unknown): User | undefined {
  return id === demoUser?.id ? demoUser : undefined; // Replace with a database lookup.
}

const app = express();
app.use(express.json());
app.use(express.static(join(import.meta.dirname, "public")));

app.get("/courier/token", async (_req, res) => {
  // Read the user from your session here. Never from the query string or body:
  // a caller who can name any user id can read that user's inbox.
  const user = sessionUser(res);
  if (!user) {
    res.status(401).json({ error: "Sign in first." });
    return;
  }

  // The inbox doesn't refresh the token, so mint a new one before the day is up.
  const { token } = await courier.auth.issueToken({
    scope: `user_id:${user.id} inbox:read:messages inbox:write:events`,
    expires_in: "1 day",
  });

  res.set("Cache-Control", "no-store").json({ userId: user.id, token });
});

app.post("/tasks/:taskId/assign", async (req, res) => {
  // Allow only the task's workspace members. The demo checks sign-in only.
  if (!sessionUser(res)) {
    res.status(401).json({ error: "Sign in first." });
    return;
  }

  const assignee = findTeammate(req.body?.assignee_id);
  if (!assignee) {
    res.status(400).json({ error: "assignee_id must be a teammate in this workspace." });
    return;
  }

  // Save the assignment here. Send after it commits, so a rollback notifies nobody.
  const task = { id: req.params.taskId, title: "Review the launch checklist" };
  const assignment = { id: randomUUID(), taskId: task.id, assigneeId: assignee.id };
  const url = `${appUrl}/tasks/${encodeURIComponent(task.id)}`;

  try {
    const requestId = await notifyTaskAssigned(assignee, { ...task, url }, assignment.id);
    res.status(201).json({ assignment, requestId });
  } catch (error) {
    // The assignment is saved, so answer 201 and leave retries to your queue.
    const retryable =
      error instanceof APIConnectionError || error instanceof RateLimitError || error instanceof ConflictError;
    console.error(`Notification failed for assignment ${assignment.id} (retryable: ${retryable}):`, error);
    res.status(201).json({ assignment, requestId: null, error: "Courier didn't accept the notification. Check the server log." });
  }
});

// Answer errors as JSON, not Express's HTML stack trace page.
app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
  if (error instanceof SyntaxError) {
    res.status(400).json({ error: "The request body isn't valid JSON." });
    return;
  }
  console.error(error);
  res.status(500).json({ error: "Something went wrong. Check the server log." });
});

const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => {
  console.log(`Listening on http://localhost:${port}`);
  if (demoUser) console.log("Demo mode: every request acts as user_123, because DEMO_EMAIL is set.");
});
```

**Take the user from your session, never from the request.** A token route that accepts a user id lets any caller read any user's inbox. Put both routes behind the auth that sets `res.locals.user`.

[Refresh the token](https://www.courier.com/docs/in-app/authenticate-users.md#5-refresh-tokens) before its day is up.

## Show in-app notifications on an Express page

Courier's inbox is the `<courier-inbox>` web component, so a static page that Express serves from `public/`, such as the quickstart's [`public/index.html`](https://github.com/trycourier/courier-express-quickstart/blob/main/public/index.html), can import it from jsDelivr.

> [accordion] public/index.html
>
> ```html public/index.html theme={null}
> <!doctype html>
> <html lang="en">
>   <head>
>     <meta charset="utf-8" />
>     <meta name="viewport" content="width=device-width, initial-scale=1" />
>     <title>Courier Express quickstart</title>
>   </head>
>   <body style="max-width: 40rem; margin: 2rem auto; font-family: system-ui, sans-serif">
>     <h1>Notifications</h1>
>     <courier-inbox height="32rem"></courier-inbox>
>
>     <script type="module">
>       // Importing it registers <courier-inbox>. jsDelivr's +esm build needs no bundler.
>       import { Courier } from "https://cdn.jsdelivr.net/npm/@trycourier/courier-ui-inbox@2.7.4/+esm";
>
>       const response = await fetch("/courier/token");
>       if (!response.ok) throw new Error(`GET /courier/token returned ${response.status}`);
>       const { userId, token } = await response.json();
>
>       Courier.shared.signIn({ userId, jwt: token });
>     </script>
>   </body>
> </html>
> ```

## Verify

Assign a demo task in the Express app and watch Courier deliver it. Run `npm run dev` and open `localhost:3000`, where the inbox signs in as `user_123`. In the cloned repo, [`npm run send`](https://github.com/trycourier/courier-express-quickstart/blob/main/scripts/send.ts) assigns a task and prints a request id.

In your own app, call the assign route. Its response carries the `requestId`:

```bash theme={null}
curl -X POST localhost:3000/tasks/task_1/assign -H "Content-Type: application/json" -d '{"assignee_id": "user_123"}'
```

The message reaches the inbox and `DEMO_EMAIL`, plus SMS with `DEMO_PHONE` set. Search [Logs](https://app.courier.com/logs) for the request id to see each channel.

| What you see | Fix |
| - | - |
| Empty inbox | Match the token's `user_id` to the send's `to.user_id` |
| SMS is `UNROUTABLE` with `DEMO_PHONE` set | Connect an SMS provider and use E.164 |
| `node: .env: not found` | Create `.env`, or `cp .env.example .env` in the clone |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. [Go live](https://www.courier.com/docs/guides/go-live.md) covers moving your Express app from Test to Production:

* **Retry from a queue.** `{ maxRetries: 0 }` fails connection errors, 429s, and 409s fast, so retry them with the same key, [starting at 60 seconds](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).
* **Switch keys.** Use a Production key with your providers connected.
* **Unset `DEMO_EMAIL`.** While it's set, every request acts as `user_123`.
* **Batch noisy events.** A journey rolls them into a [daily digest](https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md).

| Task | Nodemailer and the Twilio SDK | With Courier |
| - | - | - |
| Add a channel | Another SDK and code path | Add it to `routing.channels` |
| Provider failover | Your own logic | [Failover](https://www.courier.com/docs/send/routing.md#failover) |
| In-app feed | An endpoint and UI you build | `<courier-inbox>` |
| Tracing | One log per provider | One [log](https://www.courier.com/docs/monitor/logs.md) per request |

## FAQ

> [accordion] How do I send email from an Express app?
>
> Sending email from an Express app with Courier takes one `client.send.message` call with `"email"` in `routing.channels`. For welcome and reset emails, see the [Next.js transactional email guide](https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md).

> [accordion] Can I keep using Nodemailer or SMTP?
>
> Courier's [SMTP integration](https://www.courier.com/docs/integrations/email/smtp.md) sends through your SMTP server while your route calls `client.send.message` instead of `transporter.sendMail`. An SMTP server that allowlists IPs needs Courier's [AWS ranges](https://www.courier.com/docs/integrations/email/overview.md#allowlist-for-aws-ip-addresses).

> [accordion] How do I send SMS from Node.js?
>
> Sending SMS from Node.js with Courier takes an E.164 `phone_number` on the recipient and `"sms"` in `routing.channels`. Connect Twilio or another [SMS provider](https://www.courier.com/docs/integrations/sms/overview.md) in Courier first.

> [accordion] How do I add an in-app notification inbox to Express?
>
> An Express app adds Courier's inbox with the `<courier-inbox>` web component and a token route for the session user. See [Add an inbox](https://www.courier.com/docs/in-app/add-an-inbox.md?lang=Web%20Components).
