Listen to Firebase Realtime Database changes
Stay organized with collections
Save and categorize content based on your preferences.
This function is triggered by a change to a Firebase Realtime Database reference. It prints the source of the change, the data, and the delta.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis function is activated when a change occurs in a Firebase Realtime Database reference.\u003c/p\u003e\n"],["\u003cp\u003eThe function's primary actions include logging the source of the database change, the data affected by the change, and the specific delta (the difference before and after the change).\u003c/p\u003e\n"],["\u003cp\u003eAuthentication for Cloud Run functions is achieved by setting up Application Default Credentials, which is detailed in a linked documentation.\u003c/p\u003e\n"],["\u003cp\u003eThe examples show how to implement this function using four different languages: Go, Java, Node.js, and Python.\u003c/p\u003e\n"]]],[],null,["# Listen to Firebase Realtime Database changes\n\nThis function is triggered by a change to a Firebase Realtime Database reference. It prints the source of the change, the data, and the delta.\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package rtdb contains a Cloud Function triggered by a Firebase Realtime Database\n // event.\n package rtdb\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n \t\"github.com/googleapis/google-cloudevents-go/firebase/databasedata\"\n \t\"google.golang.org/protobuf/encoding/protojson\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"HelloRTDB\", HelloRTDB)\n }\n\n // HelloRTDB handles changes to a Firebase RTDB.\n func HelloRTDB(ctx context.Context, e event.Event) error {\n \tunmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true}\n\n \tvar data databasedata.ReferenceEventData\n \tif err := unmarshalOptions.Unmarshal(e.Data(), &data); err != nil {\n \t\treturn fmt.Errorf(\"Unmarshal: %w\", err)\n \t}\n \tlog.Printf(\"Function triggered by change to: %v\", e.Source())\n \tlog.Printf(\"Data: %+v\", data.GetData())\n \tlog.Printf(\"Delta: %+v\", data.GetDelta())\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import com.google.cloud.functions.CloudEventsFunction;\n import com.google.events.firebase.database.v1.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html;\n import com.google.protobuf.util.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html;\n import io.cloudevents.CloudEvent;\n import java.nio.charset.StandardCharsets;\n import java.util.logging.Logger;\n\n public class FirebaseRtdb implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(FirebaseRtdb.class.getName());\n\n @Override\n public void accept(CloudEvent event) throws Exception {\n if (event.getData() == null) {\n logger.info(\"No data found in event\");\n return;\n }\n\n https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html.Builder builder = https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html.newBuilder();\n https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html.https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.Parser.html jsonParser = https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.html.parser().https://cloud.google.com/java/docs/reference/protobuf/latest/com.google.protobuf.util.JsonFormat.Parser.html#com_google_protobuf_util_JsonFormat_Parser_ignoringUnknownFields__();\n jsonParser.merge(new String(event.getData().toBytes(), StandardCharsets.UTF_8), builder);\n https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html data = builder.build();\n\n logger.info(\"Function triggered by change to: \" + event.getSource().toString());\n\n if (data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_hasDelta__()) {\n logger.info(\"Delta: \" + data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_getDelta__().toString());\n }\n\n if (data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_hasData__()) {\n logger.info(\"Data: \" + data.https://cloud.google.com/java/docs/reference/google-cloudevent-types/latest/com.google.events.firebase.database.v1.ReferenceEventData.html#com_google_events_firebase_database_v1_ReferenceEventData_getData__().toString());\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Cloud Event Function triggered by a change to a Firebase RTDB reference.\n *\n * @param {!Object} event The Cloud Functions event.\n */\n const functions = require('@google-cloud/functions-framework');\n\n functions.cloudEvent('helloRTDB', event =\u003e {\n console.log(`Function triggered by change to: ${event.source}`);\n console.log('Data:');\n console.log(JSON.stringify(event.data.data, null, 2));\n console.log('Delta:');\n console.log(JSON.stringify(event.data.delta, null, 2));\n });\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import json\n\n from cloudevents.http import CloudEvent\n import functions_framework\n\n\n @functions_framework.cloud_event\n def hello_rtdb(event: CloudEvent) -\u003e None:\n \"\"\"Triggered by a change to a Firebase RTDB reference.\n Args:\n event: Cloud Event triggered by change to Firebase Real Time Database.\n \"\"\"\n print(f\"Function triggered by change to: {event['source']}\")\n print(\"Data:\")\n print(json.dumps(event.data[\"data\"]))\n print(\"Delta:\")\n print(json.dumps(event.data[\"delta\"]))\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]