In Cloud Functions for Firebase, what does a 2nd-gen Firestore trigger such as onDocumentCreated or onDocumentUpdated give your handler, and when does it fire?
answer
- a document path with wildcards
- event.params from the path
- one snapshot, or before and after
- no-op writes stay silent
basics
~20 sA Firestore trigger fires when a document matching its path is created, updated, deleted or written. The handler gets an event holding a snapshot, or a before and after pair for updates, plus the wildcard values in event.params.
solid answer
~40 sYou import `onDocumentCreated`, `onDocumentUpdated`, `onDocumentDeleted` or `onDocumentWritten` from `firebase-functions/firestore` and give it a document path such as `"orders/{orderId}"`. The path must end at a document, and wildcard values appear in `event.params`. Created and deleted events carry one snapshot in `event.data`; updated and written events carry a `Change` with `before` and `after`. The trigger runs as a service account, so Admin SDK reads and writes inside it are not checked by Security Rules. Three behaviours catch people early: a no-op write fires nothing and there are no per-field triggers, a change in a subcollection does not fire the parent's trigger, and writing back to the triggering document fires the trigger again, so the handler must compare `before` and `after` and exit when nothing changed.
code
typescript · 17 linesimport { onDocumentUpdated } from "firebase-functions/firestore";
import { logger } from "firebase-functions";
export const orderStatusChanged = onDocumentUpdated("orders/{orderId}", async (event) => {
const change = event.data;
if (!change) {
return;
}
const before = change.before.data();
const after = change.after.data();
// The write below fires this trigger again; this comparison is what ends the loop.
if (before.status === after.status) {
return;
}
logger.info(`Order ${event.params.orderId}: ${before.status} -> ${after.status}`);
await change.after.ref.set({ statusChangedAt: new Date() }, { merge: true });
});go deeper
Recall the four trigger names, that the path ends at a document, and where the wildcard values and the before and after snapshots live on the event.
Explain why no-op writes and subcollection changes fire nothing, why Admin SDK writes skip Security Rules, and how a write back to the same document loops.
Show you design handlers for unordered, at-least-once delivery and always guard the self-write case with a before and after comparison.
Weigh which derived data belongs in triggers at all, given that every write to a busy collection becomes a billed invocation that runs after the write is visible.
## The four document events Cloud Functions for Firebase reacts to Firestore writes with handlers imported from `firebase-functions/firestore`, the 2nd-gen API. Each binds a **document path** to an **event type**: | Trigger | Fires when | `event.data` holds | |---|---|---| | `onDocumentCreated` | a document is written for the first time | the new snapshot | | `onDocumentUpdated` | an existing document has any value changed | a `Change` with `before` and `after` | | `onDocumentDeleted` | a document is deleted | the snapshot as it was | | `onDocumentWritten` | any of the three above | a `Change`; `before` or `after` may not exist | Each also has a `WithAuthContext` variant, such as `onDocumentCreatedWithAuthContext`, whose event adds `authType` and `authId` describing the principal that made the write. ## Paths and wildcards - A path names one document (`"config/app"`) or a pattern with `{wildcards}` in place of IDs, such as `"orders/{orderId}"`. - The pattern must always end at a **document**. `"users/{userId}/{collectionId}"` is invalid because its last segment is a collection; `"users/{userId}/{collectionId}/{docId}"` is valid. - Wildcard values land in **`event.params`**: writing `orders/A17` under a trigger on `"orders/{orderId}"` gives `event.params.orderId === "A17"`. - A pattern matches one depth only. A trigger on `"users/{userId}"` does **not** fire when a document in `users/marie/orders` changes; that subcollection needs its own trigger. - A trigger belongs to one database. The `database` option selects a named database, which only 2nd gen supports. ## What else the event carries A 2nd-gen Firestore event is a CloudEvent, so besides `data` and `params` it has `event.id` (unique per event, the natural de-duplication key), `event.time`, `event.document` (the full path), and `database`, `namespace`, `location` and `project`. In TypeScript `event.data` is typed as possibly `undefined`, and the docs' own samples start with a guard. The `WithAuthContext` variants add `authType`, one of `service_account`, `api_key`, `system`, `unauthenticated` or `unknown`, and an optional `authId`; they describe the principal behind the write, not a substitute for storing the user's uid in the document. ## Reading and writing from a handler - Read fields with `event.data.data()` for created and deleted events, or `event.data.before.data()` and `event.data.after.data()` for updated and written ones. - Write back through the snapshot's `ref`, or reach any other document with the Admin SDK (`getFirestore()` from `firebase-admin/firestore`). - **Security Rules do not apply** to these reads and writes: the function runs as a service account with full access, so the handler owns its own checks. - Return or `await` every promise. Code that runs after the function finishes gets no CPU and makes no progress. ## Delivery facts to learn early 1. **No-op writes are silent.** An update that leaves the data unchanged produces no update or write event, and there are no per-field triggers, so compare `before` and `after` in code. 2. **Order is not guaranteed.** Rapid changes to one document can invoke the function out of order. 3. **At least once.** One event can produce more than one invocation, so handlers must tolerate duplicates. 4. **Self-triggering loops.** A handler that writes to the document it listens on fires itself again and must exit when nothing needs to change. The code example shows the habits together: a guard on `undefined`, a before-and-after comparison, a write back to the same document, and the early return that ends the loop on the second run. ## Testing triggers locally Run the Firestore and Functions emulators together from the Emulator Suite: a write to the emulated database fires the emulated trigger, so the loop guard, the wildcard parsing and the `undefined` checks can all be exercised without deploying. A unit test can also call the wrapped handler directly with a hand-built event. ## Other event sources at a glance | Source | 2nd-gen handlers | Worth knowing | |---|---|---| | Firebase Authentication | `onUserCreated`, `onUserDeleted` from `firebase-functions/identity` | Preview (beta) in firebase-functions 7.4.0; a first sign-in with a custom token fires no create event; a bulk `deleteUsers` call fires no delete events | | Cloud Storage | `onObjectFinalized`, `onObjectDeleted`, `onObjectArchived`, `onObjectMetadataUpdated` | a `bucket` option targets a non-default bucket | | Schedule | `onSchedule` | Unix crontab or App Engine syntax, such as `"every day 00:00"` | Blocking functions such as `beforeUserCreated` and `beforeUserSignedIn` are different again: they run synchronously inside sign-up or sign-in, can refuse it, and need Firebase Authentication with Identity Platform. In the order app, `onDocumentCreated("orders/{orderId}")` is where stock is reserved and the confirmation is queued, and an `onDocumentUpdated` trigger like the one above reacts to status changes. Both run on the server, so a phone that goes offline after placing the order still gets the work done once its write reaches Firestore.
- Why does a trigger on users/{userId} stay silent when users/marie/orders/o1 changes?A trigger path matches documents at exactly that depth. `users/marie/orders/o1` is a document in a subcollection, so it matches `users/{userId}/orders/{orderId}`, not `users/{userId}`. Add a trigger on the deeper path, or `users/{userId}/{collectionId}/{docId}` to catch every subcollection one level down; a path that ends at a collection is invalid.
- An update rewrites a field with the value it already had. Does onDocumentUpdated fire?No. A write that leaves the document's data unchanged generates neither an update nor a write event. You also cannot subscribe to single fields, so a trigger that cares about `status` fires for any changed field and must compare `before.status` with `after.status` itself.
- A trigger on users/{userId} also fires for writes in its subcollections.
- onDocumentUpdated can be bound to a single field.
- Writes made from a trigger are checked against Security Rules.
- Firestore events reach the function in the order the writes happened.
- Writing back to the triggering document is always safe.
Assumes firebase-functions 7.4.0 (Firebase as of 2026-10-09), where the 2nd-gen Auth triggers onUserCreated and onUserDeleted are Preview (beta).