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
Python
Go
Java
C#
Deploy the Hello Firestore function
If you haven't already done so, set up your Firestore database.
After deploying a function, you can configure a trigger using the Google Cloud console, Google Cloud CLI, or Terraform.
Console
When you use the Google Cloud console to create a function, you can also add a trigger to your function. Follow these steps to create a trigger for your function:
In the Google Cloud console, go to Cloud Run:
Click Write a function, and enter the function details. For more information about configuring functions during deployment, see Deploy functions.
In the Trigger section, click Add trigger.
Select Firestore trigger.
In the Eventarc trigger pane, modify the trigger details as follows:
Enter a name for the trigger in the Trigger name field, or use the default name.
Select a Trigger type from the list:
Google Sources to specify triggers for Pub/Sub, Cloud Storage, Firestore, and other Google event providers.
Third-party to integrate with non-Google providers that offer an Eventarc source. For more information, see Third-party events in Eventarc.
Select Cloud Firestore from the Event provider list, to select a product that provides the type of event for triggering your function. For the list of event providers, see Event providers and destinations.
Select type=google.cloud.firestore.document.v1.written from the Event type list. Your trigger configuration varies depending on the supported event type. For more information, see Event types.
Leave the Event data content type field as is.
In the Filters section, select a database, operation and attribute values, or use the default selections.
If the Region field is enabled, select a location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.
In the Service account field, select a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Compute Engine default service account.
Optionally, specify the Service URL path to send the incoming request to. This is the relative path on the destination service to which the events for the trigger should be sent. For example:
/,/route,route, androute/subroute.Optionally, to enable retries if the delivery attempt fails, select the Enable retry on failure checkbox; otherwise, the default behavior is a single delivery attempt with no retries. For more information, see Retry events.
Once you've completed the required fields, click Save trigger.
Click Create.
In the Source tab, edit the source code if needed, then select Save and redeploy.
gcloud
When you create a function using the gcloud CLI, you must first deploy your function, and then create a trigger. Follow these steps to create a trigger for your function:
Run the following command in the directory that contains the sample code to deploy your function:
gcloud run deploy FUNCTION \ --source . \ --function FUNCTION_ENTRYPOINT \ --base-image BASE_IMAGE_ID \ --region REGIONReplace the following:
FUNCTION: the name of the function you are deploying. You can omit this parameter entirely, but you will be prompted for the name if you omit it.FUNCTION_ENTRYPOINT: the entry point to your function in your source code. This is the code Cloud Run executes when your function runs. The value of this flag must be a function name or fully-qualified class name that exists in your source code.BASE_IMAGE_ID: the base image environment for your function. For more details about base images and the packages included in each image, see Runtimes base images.REGION: the Google Cloud region where you want to deploy your function. For example,europe-west1.
Run the following command to create a trigger that filters and routes events:
gcloud eventarc triggers create TRIGGER_NAME \ --location=LOCATION \ --destination-run-service=FUNCTION \ --destination-run-region=DESTINATION_RUN_REGION \ --event-filters="type=EVENT_FILTER_TYPE" \ --event-filters=database='(default)' \ --event-data-content-type=application/protobuf \ --event-filters-path-pattern=document='users/{username}' \ --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.Replace the following:
TRIGGER_NAME: the ID of the trigger or a fully qualified identifier.LOCATION: the location of the Eventarc trigger. Alternatively, you can set theeventarc/locationproperty; for example,gcloud config set eventarc/location us-central1.To avoid any performance and data residency issues, the location must match the location of the Google Cloud service that is generating events. For more information, see Eventarc locations.
-
FUNCTION: the name of the deployed Cloud Run function that receives the events for the trigger. -
DESTINATION_RUN_REGION: (optional) the Cloud Run location in which the destination Cloud Run function can be found. If not specified, it is assumed that the function is in the same region as the trigger. EVENT_FILTER_TYPE: the identifier of the event. An event is generated when an API call for the method succeeds. For long-running operations, the event is only generated at the end of the operation, and only if the action is performed successfully. For a list of supported event types, see Google event types supported by Eventarc.SERVICE_ACCOUNT_NAME: the name of your user-managed service account.PROJECT_ID: your Google Cloud project ID.
Notes:
- After a trigger is created, the event filter type can't be changed. For a different event type, you must create a new trigger.
--event-filters=type=google.cloud.firestore.document.v1.writtenspecifies that the function is triggered when a document is created, updated or deleted, per the event type.--event-filters=database='(default)'specifies the Firebase database. For the default database name, use(default).--event-filters-path-pattern=document='users/{username}'provides the path pattern of the documents that should be monitored for relevant changes. This path pattern states that all documents in theuserscollection should be monitored. For more information, see Understand path patterns.- Optionally, to specify a single event delivery attempt with no retries, use the
--max-retry-attemptsflag. The only valid value is1. If you omit the flag, the standard retry behavior applies. For more information, see Retry events. - Other flags are available. For more information, see
gcloud eventarc triggers create.
Terraform
To create an Eventarc trigger for a Cloud Run function, see Create a trigger using Terraform.
Test the Hello Firestore function
To test the Hello Firestore function, set up a collection called
users in your Firestore database:
In the Google Cloud console, go to the Firestore databases page:
Click Start a collection.
Specify
usersas the collection ID.To start adding the collection's first document, under Add its first document accept the auto-generated Document ID.
Add at least one field for the document, specifying a name and value. For example, in Field name, enter
username, and in Field value, enterrowan.When you're done, click Save.
This action creates a new document, thereby triggering your function.
To confirm that your function was triggered, click the linked name of the function in the Google Cloud console Cloud Run Overview page to open the Service details page.
In the Observability tab, select the Logs tab and look for the following string:
Function triggered by change to: //firestore.googleapis.com/projects/your-project-id/databases/(default)'
Example 2: Convert to Uppercase function
The following example retrieves the value added by the user, converts the string at that location to uppercase, and replaces the value with the uppercase string:
Node.js
Use protobufjs to decode the event
data. Include the google.events.cloud.firestore.v1
data.proto
in your source.
Python
Go
Java
C#
Deploy the Convert to Uppercase function
If you haven't already done so, set up your Firestore database.
After deploying a function, you can configure a trigger using the Google Cloud console, Google Cloud CLI, or Terraform.
Console
When you use the Google Cloud console to create a function, you can also add a trigger to your function. Follow these steps to create a trigger for your function:
In the Google Cloud console, go to Cloud Run:
Click Write a function, and enter the function details. For more information about configuring functions during deployment, see Deploy functions.
In the Trigger section, click Add trigger.
Select Firestore trigger.
In the Eventarc trigger pane, modify the trigger details as follows:
Enter a name for the trigger in the Trigger name field, or use the default name.
Select a Trigger type from the list:
Google Sources to specify triggers for Pub/Sub, Cloud Storage, Firestore, and other Google event providers.
Third-party to integrate with non-Google providers that offer an Eventarc source. For more information, see Third-party events in Eventarc.
Select Firestore from the Event provider list, to select a product that provides the type of event for triggering your function. For the list of event providers, see Event providers and destinations.
Select type=google.cloud.firestore.document.v1.written from the Event type list. Your trigger configuration varies depending on the supported event type. For more information, see Event types.
Leave the Event data content type field as is.
In the Filters section, select a database, operation and attribute values, or use the default selections. If you named your database, enter the name in the Attribute value 1 field.
If the Region field is enabled, select a location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.
In the Service account field, select a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Compute Engine default service account.
Optionally, specify the Service URL path to send the incoming request to. This is the relative path on the destination service to which the events for the trigger should be sent. For example:
/,/route,route, androute/subroute.Optionally, to enable retries if the delivery attempt fails, select the Enable retry on failure checkbox; otherwise, the default behavior is a single delivery attempt with no retries. For more information, see Retry events.
Once you've completed the required fields, click Save trigger.
Click Create.
In the Source tab, edit the source code if needed, then select Save and redeploy.
gcloud
When you create a function using the gcloud CLI, you must first deploy your function, and then create a trigger. Follow these steps to create a trigger for your function:
Run the following command in the directory that contains the sample code to deploy your function:
gcloud run deploy FUNCTION \ --source . \ --function FUNCTION_ENTRYPOINT \ --base-image BASE_IMAGE_ID \ --region REGIONReplace the following:
FUNCTION: the name of the function you are deploying. You can omit this parameter entirely, but you will be prompted for the name if you omit it.FUNCTION_ENTRYPOINT: the entry point to your function in your source code. This is the code Cloud Run executes when your function runs. The value of this flag must be a function name or fully-qualified class name that exists in your source code.BASE_IMAGE_ID: the base image environment for your function. For more details about base images and the packages included in each image, see Runtimes base images.REGION: the Google Cloud region where you want to deploy your function. For example,europe-west1.
Run the following command to create a trigger that filters and routes events:
gcloud eventarc triggers create TRIGGER_NAME \ --location=LOCATION \ --destination-run-service=FUNCTION \ --destination-run-region=DESTINATION_RUN_REGION \ --event-filters=type=google.cloud.firestore.document.v1.written \ --event-filters=database='(default)' \ --event-data-content-type=application/protobuf \ --event-filters-path-pattern=document='messages/{pushId}' \ --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.Replace the following:
TRIGGER_NAME: the ID of the trigger or a fully qualified identifier.LOCATION: the location of the Eventarc trigger. Alternatively, you can set theeventarc/locationproperty; for example,gcloud config set eventarc/location us-central1.To avoid any performance and data residency issues, the location must match the location of the Google Cloud service that is generating events. For more information, see Eventarc locations.
-
FUNCTION: the name of the deployed Cloud Run function that receives the events for the trigger. -
DESTINATION_RUN_REGION: (optional) the Cloud Run location in which the destination Cloud Run function can be found. If not specified, it is assumed that the function is in the same region as the trigger. EVENT_FILTER_TYPE: the identifier of the event. An event is generated when an API call for the method succeeds. For long-running operations, the event is only generated at the end of the operation, and only if the action is performed successfully. For a list of supported event types, see Google event types supported by Eventarc.SERVICE_ACCOUNT_NAME: the name of your user-managed service account.PROJECT_ID: your Google Cloud project ID.
Notes:
- After a trigger is created, the event filter type can't be changed. For a different event type, you must create a new trigger.
--event-filters=type=google.cloud.firestore.document.v1.writtenspecifies that the function is triggered when a document is created, updated or deleted, per the event type.--event-filters=database='(default)'specifies the Firebase database. For the default database name, use(default).--event-filters-path-pattern=document='users/{username}'provides the path pattern of the documents that should be monitored for relevant changes. This path pattern states that all documents in theuserscollection should be monitored. For more information, see Understand path patterns.- Optionally, to specify a single event delivery attempt with no retries, use the
--max-retry-attemptsflag. The only valid value is1. If you omit the flag, the standard retry behavior applies. For more information, see Retry events. - Other flags are available. For more information, see
gcloud eventarc triggers create.
Terraform
To create an Eventarc trigger for a Cloud Run function, see Create a trigger using Terraform.
Use the other fields as is:
--event-filters=type=google.cloud.firestore.document.v1.writtenspecifies that the function is triggered when a document is created, updated or deleted, per thegoogle.cloud.firestore.document.v1.writtenevent type.--event-filters=database='(default)'specifies the Firestore database. For the default database name, use(default).--event-filters-path-pattern=document='messages/{pushId}'provides the path pattern of the documents that should be monitored for relevant changes. This path pattern states that all documents in themessagescollection should be monitored. For more information, see Understand path patterns.
Test the Convert to Uppercase function
To test the Convert to Uppercase function you just deployed, set up
a collection called messages in your
Firestore database:
In the Google Cloud console, go to the Firestore databases page:
Select the Database ID for your Firestore database.
Click Start a collection.
Specify
messagesas the collection ID.To start adding the collection's first document, under Add its first document accept the auto-generated Document ID.
To trigger your deployed function, add a document where the Field name is
originaland the Field value isminka.When you save the document, you can see the lowercase word in the value field convert to uppercase.
If you subsequently edit the field value to contain lowercase letters, that triggers the function again, converting all lowercase letters to uppercase.
Limitations for functions
- Ordering is not guaranteed. Rapid changes can trigger function invocations in an unexpected order.
- Events are delivered at least once, but a single event may result in multiple function invocations. Avoid depending on exactly-once mechanics, and write idempotent functions.
- A trigger is associated with a single database. You cannot create a trigger that matches multiple databases.
- Deleting a database does not automatically delete any triggers for that database. The trigger stops delivering events but continues to exist until you delete the trigger.