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

# Send a push from Firestore

> Turn a Firestore document write into a push that falls back to email, from a Cloud Function that addresses a user instead of a device token.

A document lands in Firestore and someone should know. This guide sends a push, and an email instead when the push can't land.

## What you'll build

```mermaid theme={null}
flowchart LR
    A["Firestore write"] --> B["Cloud Function"]
    B --> C{"Push delivers?"}
    C -->|Yes| D["Push arrives"]
    C -->|No| E["Email instead"]
```

## Prerequisites

* [A Courier Test API key](https://app.courier.com/~/test/platform/api-keys)
* [Push already working](https://www.courier.com/docs/guides/set-up-mobile-push.md), with FCM connected and device tokens syncing
* A published [template](https://www.courier.com/docs/design/templates/overview.md) with push and email content

## What this adds over calling FCM yourself

You already have Firebase, so calling FCM from the same function is one line shorter. Here's what the extra hop buys:

**You address a person, not a device.** FCM needs a registration token. Courier needs a `user_id`, and resolves the tokens itself, including the case where someone has three devices and one stale token.

**A failed push becomes an email.** FCM can tell you a token was rejected. It can't then reach the person another way. One `routing` line does.

**Preferences apply without a conditional.** If the recipient muted this notification type, Courier filters it. With raw FCM that check is code you write and maintain at every call site.

**One log covers both channels.** A push that failed and an email that succeeded are the same message in [Logs](https://app.courier.com/logs), not two systems to correlate.

If none of those matter for a given notification, call FCM directly. They usually start mattering around the second channel.

## Set it up

**1. Install and store the key**

In your functions directory:

```bash theme={null}
npm install firebase-functions @trycourier/courier
firebase functions:secrets:set COURIER_API_KEY
```

**2. Write the trigger**

This is a 2nd-gen Firestore trigger. The path carries a wildcard, and its value arrives on `event.params`.

```javascript functions/index.js lines theme={null}
const { onDocumentCreated } = require("firebase-functions/v2/firestore");
const Courier = require("@trycourier/courier");

exports.onNewComment = onDocumentCreated(
  { document: "documents/{docId}/comments/{commentId}", secrets: ["COURIER_API_KEY"] },
  async (event) => {
    const snapshot = event.data;
    if (!snapshot) return; // deleted before the function ran

    const comment = snapshot.data();
    const { docId } = event.params;

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

    await courier.send.message({
      message: {
        to: { user_id: comment.recipientId },
        template: "nt_01kx4h2jdafq8bk9aftxak4b40",
        // Try push through APNs, then FCM. If neither lands, send the email.
        routing: { method: "single", channels: ["apn", "firebase-fcm", "email"] },
        data: {
          author: comment.authorName,
          excerpt: comment.text.slice(0, 140),
          document_id: docId,
        },
      },
    });
  },
);
```

**`routing: { method: "single", channels: ["apn", "firebase-fcm", "email"] }`** walks the list and stops at the first entry that works: APNs, then FCM, then email as the failover. The push providers are named by key because the `push` channel also includes Courier Inbox, which would take the message before email. Swap to `all` and push and email both go out every time.

**`if (!snapshot) return`** guards the case where the document is gone by the time the function runs. Firestore triggers aren't transactional with the write.

**3. Deploy**

```bash theme={null}
firebase deploy --only functions:onNewComment
```

## Verify

**1. Write a document**

Add a comment document under a path matching the trigger, from your app or the Firebase console.

**2. Check the function ran**

```bash theme={null}
firebase functions:log --only onNewComment
```

**3. Confirm which channel delivered**

Open [Logs](https://app.courier.com/logs). The timeline names the channel that delivered. To prove the fallback, remove the user's device tokens and write again. The same send should arrive by email.

## Adapt it for other writes

| Trigger | What to send |
| :- | :- |
| `onDocumentCreated` | The new thing happened. A comment, an order, an invite |
| `onDocumentUpdated` | Compare `event.data.before` to `event.data.after` and send only when something meaningful moved |
| `onDocumentDeleted` | A cancellation or removal confirmation |

The update case is the one to be careful with. A trigger on every write fires on fields nobody cares about, so compare before and after and return early. That is the difference between a useful alert and a reason to mute your app.

For fan-out, when many people are watching the document rather than one, address a list instead of a user. [Notify everyone watching](https://www.courier.com/docs/guides/notify-everyone-watching.md) covers that shape.
