Trigger functions with Firestore documents

This guide shows examples of functions that are triggered when you make changes to a document inside of a specified collection.

Before you begin

Before you run the sample code in this guide, you'll need to do the following:

Examples

The following examples demonstrate how to write functions that respond to a Firestore trigger.

Example 1: Hello Firestore function

The following sample prints the fields of a triggering Firestore event:

Node.js

/**
 * Cloud Event Function triggered by a change to a Firestore document.
 */
const functions = require('@google-cloud/functions-framework');
const protobuf = require('protobufjs');

functions.cloudEvent('helloFirestore', async cloudEvent => {
  console.log(`Function triggered by event on: ${cloudEvent.source}`);
  console.log(`Event type: ${cloudEvent.type}`);

  console.log('Loading protos...');
  const root = await protobuf.load('data.proto');
  const DocumentEventData = root.lookupType(
    'google.events.cloud.firestore.v1.DocumentEventData'
  );

  console.log('Decoding data...');
  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);

  console.log('\nOld value:');
  console.log(JSON.stringify(firestoreReceived.oldValue,