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

# Batch notifications into a daily digest in Node.js

> Send a daily digest email instead of one email per comment from Node.js. A Courier journey's Batch node collects each user's events and sends them as one.

Send each user one daily digest email from Node.js by invoking a Courier journey per comment. The journey's Batch node holds the comments and sends one email when the window closes, instead of an email per comment.

```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: "Hello from Courier", body: "Your Node.js app can send email." },
  },
});

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-node-digest-quickstart](https://github.com/trycourier/courier-node-digest-quickstart)
>
> The finished Node.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 Node.js app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
Add a daily comment digest to this Node.js app with Courier, instead of one email per comment.
Follow https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md
and the reference app at https://github.com/trycourier/courier-node-digest-quickstart.
Use @trycourier/courier and read COURIER_API_KEY from the environment.
Define the journey (API trigger, per-user Batch node, email send node) in a setup script,
and invoke it once per comment with an Idempotency-Key built from the comment id.
When done, run the setup script with DIGEST_WINDOW=PT1M, post three test comments, and show me the run ids.
```

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 the client in `lib/courier.ts`, not raw HTTP.
* Read `COURIER_API_KEY` from the environment on the server. Never send it to a browser or commit `.env`.
* Invoke the journey once per comment, with an `Idempotency-Key` built from the comment's database id: `comment-<id>`.
* Invoke from the route that saves the comment, after it commits. The Batch node, not your code, decides when to send.
* Change the journey or template in `scripts/setup.ts` and rerun `npm run setup`, which overwrites console edits.
* Never send the digest through your email provider directly. The journey's send node routes it.

## What you'll build

This Node.js app turns each new comment into one Courier journey invoke:

* **A setup script** that creates the journey, its per-user Batch node, and the digest template
* **An Express endpoint** that invokes the journey once per comment

## 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

* [A connected email provider](https://www.courier.com/docs/integrations/email/overview.md)

## Clone the finished Node.js app

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

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

The steps below add or change these files:

| File | What it does |
| - | - |
| `lib/courier.ts` | The client and `notifyNewComment` |
| `scripts/setup.ts` | Creates the journey and template |
| `server.ts` | The Express comment endpoint |
| `package.json` | Scripts that load `.env` |

## Install the Courier Node.js SDK and Express

The Courier Node.js SDK is `@trycourier/courier` on npm:

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

Set `"type": "module"` and add these scripts to [`package.json`](https://github.com/trycourier/courier-node-digest-quickstart/blob/main/package.json), which load `.env` with `tsx --env-file`. To type-check with `tsc`, copy the repo's [`tsconfig.json`](https://github.com/trycourier/courier-node-digest-quickstart/blob/main/tsconfig.json), which allows `.ts` imports:

```json theme={null}
"scripts": {
  "setup": "tsx --env-file=.env scripts/setup.ts",
  "dev": "tsx watch --env-file=.env server.ts",
  "send": "tsx --env-file=.env scripts/send.ts"
}
```

Put your key and address in `.env`:

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
COURIER_DIGEST_JOURNEY_ID=
DIGEST_WINDOW=P1D
```

## Create the digest notify function in Node.js

`notifyNewComment` invokes the Courier journey with `client.journeys.invoke`, which calls [`POST /journeys/{templateId}/invoke`](https://www.courier.com/docs/api-reference/journeys/invoke-a-journey) (`templateId` is the journey's id), once per comment with an [idempotency key](https://www.courier.com/docs/send/overview.md#idempotency).

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

export const courier = new Courier({ apiKey: process.env.COURIER_API_KEY });

export type Comment = {
  id: string;
  post_title: string;
  commenter_name: string;
  text: string;
};

export type Recipient = {
  id: string;
  email: string;
};

/**
 * Adds one comment to the post author's digest.
 *
 * Call it once per comment. The journey's Batch node holds every comment for
 * the same user and sends one email when the window closes, so this function
 * never decides whether to send now or later.
 */
export async function notifyNewComment(recipient: Recipient, comment: Comment) {
  const journeyId = process.env.COURIER_DIGEST_JOURNEY_ID;
  if (!journeyId) {
    throw new Error("COURIER_DIGEST_JOURNEY_ID is not set. Run `npm run setup` first.");
  }

  const { runId } = await courier.journeys.invoke(journeyId, {
    user_id: recipient.id,
    // Merged into the stored profile, so the digest knows where to send.
    profile: { email: recipient.email },
    // Each invoke's `data` becomes one item in `data.batch.items`.
    data: {
      comment_id: comment.id,
      post_title: comment.post_title,
      commenter_name: comment.commenter_name,
      comment_text: comment.text,
    },
    // A retry for the same comment returns the first run instead of adding it twice.
    "Idempotency-Key": `comment-${comment.id}`,
  });

  return runId;
}
```

## Define the digest journey with a Batch node

The Node.js setup script keeps the Courier journey in your repo, following [Build with the API](https://www.courier.com/docs/journeys/build.md#build-with-the-api).

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

/**
 * Creates the comment digest journey, or updates it when
 * COURIER_DIGEST_JOURNEY_ID is set. Safe to rerun after any edit below.
 *
 *   trigger (API invoke) -> batch (per user) -> send (digest email) -> exit
 */

const JOURNEY_NAME = "Comment digest";
const TEMPLATE_NAME = "Comment digest email";

// How long a batch collects before the digest sends. P1D is a daily digest.
// Set DIGEST_WINDOW=PT1M and rerun this script to test in a minute.
const WINDOW = process.env.DIGEST_WINDOW || "P1D";

// The digest email. `data.batch.count` is every comment in the batch, and the
// looped text element repeats once per retained comment in `data.batch.items`.
const notification = {
  name: TEMPLATE_NAME,
  tags: [],
  brand: null,
  subscription: null,
  content: {
    version: "2022-01-01" as const,
    // Strict scope: every variable path starts with `data.`.
    scope: "strict" as const,
    elements: [
      {
        type: "channel" as const,
        channel: "email",
        elements: [
          { type: "meta" as const, title: "New comments on your posts" },
          { type: "text" as const, content: "Comments since your last digest: {{data.batch.count}}" },
          {
            type: "text" as const,
            loop: "data.batch.items",
            content: "{{$.item.commenter_name}} on {{$.item.post_title}}: {{$.item.comment_text}}",
          },
        ],
      },
    ],
  },
};

function nodes(templateId?: string): Courier.JourneyNode[] {
  const trigger: Courier.JourneyNode = { type: "trigger", trigger_type: "api-invoke" };
  const exit: Courier.JourneyNode = { type: "exit" };
  if (!templateId) return [trigger, exit];

  return [
    trigger,
    {
      type: "batch",
      scope: "user",
      // Both windows are WINDOW, so each digest sends one WINDOW after its first
      // comment. Shorten wait_period to send sooner when comments stop coming.
      // Quiet window: release once no comment has arrived for this long (1 minute to 1 day).
      wait_period: WINDOW,
      // Hard ceiling from the first comment (at least wait_period, at most 7 days).
      max_wait_period: WINDOW,
      max_items: 100,
      // Keep the first 10 comments for the email. batch.count still counts them all.
      retain: { type: "first", count: 10 },
    },
    { type: "send", channel: "email", message: { template: templateId } },
    exit,
  ];
}

async function main() {
  // 1. The journey. A send node needs a template id, so a new journey starts empty.
  let journeyId = process.env.COURIER_DIGEST_JOURNEY_ID;
  if (!journeyId) {
    const journey = await courier.journeys.create({ name: JOURNEY_NAME, nodes: nodes() });
    journeyId = journey.id;
  }

  // 2. The digest template, scoped to this journey. Created once, replaced on reruns.
  const { results } = await courier.journeys.templates.list(journeyId);
  const existing = results.find((template) => template.name === TEMPLATE_NAME);
  const templateId = existing
    ? (await courier.journeys.templates.replace(existing.id, { templateId: journeyId, notification })).id
    : (await courier.journeys.templates.create(journeyId, { channel: "email", notification })).id;

  // A run sends the template's published version, so publish it before the journey.
  await courier.journeys.templates.publish(templateId, { templateId: journeyId });

  // 3. Wire trigger -> batch -> send -> exit, then publish so new invokes use it.
  await courier.journeys.replace(journeyId, { name: JOURNEY_NAME, nodes: nodes(templateId) });
  await courier.journeys.publish(journeyId);

  console.log(`Published "${JOURNEY_NAME}" with a ${WINDOW} batch window.`);
  if (!process.env.COURIER_DIGEST_JOURNEY_ID) {
    console.log("\nAdd this line to .env, then start the server:\n");
    console.log(`COURIER_DIGEST_JOURNEY_ID=${journeyId}\n`);
  }
}

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

Run `npm run setup`, copy the `COURIER_DIGEST_JOURNEY_ID=...` line it prints into `.env`, and restart `npm run dev` if it's running. The [Batch node reference](https://www.courier.com/docs/journeys/nodes/batch.md) covers every field.

## Call the digest from your Express comment endpoint

The Express comment route saves the comment, then calls `notifyNewComment` with the post's author as the Courier recipient.

```ts server.ts lines theme={null}
import { randomUUID } from "node:crypto";
import express from "express";
import { notifyNewComment } from "./lib/courier.ts";

const app = express();
app.use(express.json());

app.post("/posts/:postId/comments", async (req, res) => {
  const { commenter_name, text } = req.body;

  // Save the comment in your database here. Its id keys the idempotent invoke.
  const comment = {
    id: randomUUID(),
    post_title: "Launch checklist",
    commenter_name,
    text,
  };

  // A real app loads the post's author from its database. The demo pins one
  // user and sends to DEMO_EMAIL so the digest reaches you.
  const postAuthor = { id: "user_123", email: process.env.DEMO_EMAIL! };

  try {
    const runId = await notifyNewComment(postAuthor, comment);
    res.status(201).json({ comment, runId });
  } catch (error) {
    // The comment is saved, so don't fail a request the client may repeat.
    // This demo only logs the failure, which leaves the comment out of the
    // digest. In your app, queue a retry keyed by the comment id: the same
    // Idempotency-Key makes a repeated invoke safe.
    console.error(`Digest invoke failed for comment ${comment.id}:`, error);
    res.status(201).json({ comment, runId: null });
  }
});

const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => {
  console.log(`Listening on http://localhost:${port}`);
});
```

## Verify

Set `DIGEST_WINDOW=PT1M` in `.env` and rerun `npm run setup` so the Courier digest sends a minute after the first comment. Then:

1. Run `npm run dev`, then post three comments from a second terminal. Each prints a run id:
   ```bash theme={null}
   for i in 1 2 3; do curl -s -X POST localhost:3000/posts/post_1/comments -H "Content-Type: application/json" -d "{\"commenter_name\": \"Kai\", \"text\": \"Comment $i\"}"; echo; done
   ```
   In the cloned repo, `npm run send` does the same.
2. Open the journey's **Logs** in [Journeys](https://app.courier.com/orchestration/journeys). The first run waits at the Batch node.
3. When the window closes, one email lists all three comments. Set `P1D` again before production.

| What you see | Fix |
| - | - |
| `401` | Copy the key from [Platform → API Keys](https://app.courier.com/settings/api-keys) |
| `channel "email" is not configured` | Use the key from your provider's environment |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. It replaces the digest queue your Node.js app would otherwise run. [Go live](https://www.courier.com/docs/guides/go-live.md) covers moving from Test to Production:

* **Run setup once per environment** and store each journey ID.
* **Link the template to a topic** so Courier applies [preferences](https://www.courier.com/docs/recipients/preferences/overview.md).
* **Log the run id** to [list its steps](https://www.courier.com/docs/api-reference/journeys/list-steps-for-a-journey-run.md).

| Task | BullMQ, Redis, and a worker | With Courier |
| - | - | - |
| Per-user windows | A delayed job per user | `wait_period` on the Batch node |
| Duplicate events | Your own dedupe table | An `Idempotency-Key` per comment |
| A second channel | Another provider SDK | Another send node, such as [Inbox](https://www.courier.com/docs/in-app/overview.md) |
| Debugging | Redis, worker, and provider logs | One [journey log](https://www.courier.com/docs/monitor/logs.md#journey-logs) per run |

## FAQ

> [accordion] How do I batch notifications in Node.js?
>
> Batching notifications in Node.js with Courier takes a journey with a Batch node and one `client.journeys.invoke` call per event.

> [accordion] How long can a digest batch wait?
>
> A Courier Batch node waits at most 7 days, set by `max_wait_period`. Its quiet window, `wait_period`, runs from 1 minute to 1 day.

> [accordion] Can each user choose a daily or weekly digest?
>
> Per-user digest schedules come from a Courier [subscription topic digest](https://www.courier.com/docs/guides/send-a-daily-digest.md). A Batch node gives every user the same window.

> [accordion] Do I need BullMQ or a cron job to send a daily digest in Node.js?
>
> A daily digest in Node.js needs no BullMQ, Redis, or cron job when a Courier Batch node holds the comments and sends the digest.
