Firebase RTDB trigger
Stay organized with collections
Save and categorize content based on your preferences.
Triggers a function when a Firebase realtime database is updated.
Explore further
For detailed documentation that includes this code sample, see the following:
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 code demonstrates how to trigger a function in response to updates in a Firebase Realtime Database.\u003c/p\u003e\n"],["\u003cp\u003eThe function captures and logs information about the database change, including the resource that triggered the event and the delta (changes).\u003c/p\u003e\n"],["\u003cp\u003eThe examples are provided in multiple programming languages: C#, Go, Java, Node.js, PHP, Python, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eTo interact with Cloud Run functions, the code uses Application Default Credentials for authentication, and the instructions to set up are provided.\u003c/p\u003e\n"],["\u003cp\u003eYou can find additional code samples for other Google Cloud products in the Google Cloud sample browser.\u003c/p\u003e\n"]]],[],null,["# Firebase RTDB trigger\n\nTriggers a function when a Firebase realtime database is updated.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Firebase Realtime Database Triggers](/functions/1stgendocs/calling/realtime-database)\n\nCode sample\n-----------\n\n### C#\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 using CloudNative.CloudEvents;\n using Google.Cloud.Functions.Framework;\n using Google.Events.Protobuf.Firebase.Database.V1;\n using Microsoft.Extensions.Logging;\n using System.Threading;\n using System.Threading.Tasks;\n\n namespace FirebaseRtdb;\n\n public class Function : ICloudEventFunction\u003cReferenceEventData\u003e\n {\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, ReferenceEventData data, CancellationToken cancellationToken)\n {\n _logger.LogInformation(\"Function triggered by change to {subject}\", cloudEvent.Subject);\n _logger.LogInformation(\"Delta: {delta}\", data.Delta);\n\n // In this example, we don't need to perform any asynchronous operations, so the\n // method doesn't need to be declared async.\n return Task.CompletedTask;\n }\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 p contains a Cloud Function triggered by a Firebase Realtime Database\n // event.\n package p\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n\n \t\"cloud.google.com/go/functions/metadata\"\n )\n\n // RTDBEvent is the payload of a RTDB event.\n type RTDBEvent struct {\n \tData interface{} `json:\"data\"`\n \tDelta interface{} `json:\"delta\"`\n }\n\n // HelloRTDB handles changes to a Firebase RTDB.\n func HelloRTDB(ctx context.Context, e RTDBEvent) error {\n \tmeta, err := metadata.https://cloud.google.com/go/docs/reference/cloud.google.com/go/functions/latest/metadata.html#cloud_google_com_go_functions_metadata_Metadata_FromContext(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"metadata.FromContext: %w\", err)\n \t}\n \tlog.Printf(\"Function triggered by change to: %v\", meta.https://cloud.google.com/go/docs/reference/cloud.google.com/go/functions/latest/metadata.html#cloud_google_com_go_functions_metadata_Resource)\n \tlog.Printf(\"%+v\", e)\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.Context;\n import com.google.cloud.functions.RawBackgroundFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonObject;\n import java.util.logging.Logger;\n\n public class FirebaseRtdb implements RawBackgroundFunction {\n private static final Logger logger = Logger.getLogger(FirebaseRtdb.class.getName());\n\n // Use GSON (https://github.com/google/gson) to parse JSON content.\n private static final Gson gson = new Gson();\n\n @Override\n public void accept(String json, Context context) {\n logger.info(\"Function triggered by change to: \" + context.resource());\n\n JsonObject body = gson.fromJson(json, JsonObject.class);\n\n boolean isAdmin = false;\n if (body != null && body.has(\"auth\")) {\n JsonObject authObj = body.getAsJsonObject(\"auth\");\n isAdmin = authObj.has(\"admin\") && authObj.get(\"admin\").getAsBoolean();\n }\n\n logger.info(\"Admin?: \" + isAdmin);\n\n if (body != null && body.has(\"delta\")) {\n logger.info(\"Delta:\");\n logger.info(body.get(\"delta\").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 * Background Function triggered by a change to a Firebase RTDB reference.\n *\n * @param {!Object} event The Cloud Functions event.\n * @param {!Object} context The Cloud Functions event context.\n */\n exports.helloRTDB = (event, context) =\u003e {\n const triggerResource = context.resource;\n\n console.log(`Function triggered by change to: ${triggerResource}`);\n console.log(`Admin?: ${!!context.auth.admin}`);\n console.log('Delta:');\n console.log(JSON.stringify(event.delta, null, 2));\n };\n\n### PHP\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 use Google\\CloudFunctions\\CloudEvent;\n\n function firebaseRTDB(CloudEvent $cloudevent)\n {\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n\n fwrite($log, 'Event: ' . $cloudevent-\u003egetId() . PHP_EOL);\n\n $data = $cloudevent-\u003egetData();\n $resource = $data['resource'] ?? '\u003cnull\u003e';\n\n fwrite($log, 'Function triggered by change to: ' . $resource . PHP_EOL);\n\n $isAdmin = isset($data['auth']['admin']) && $data['auth']['admin'] == true;\n\n fwrite($log, 'Admin?: ' . var_export($isAdmin, true) . PHP_EOL);\n fwrite($log, 'Delta: ' . json_encode($data['delta'] ?? '') . PHP_EOL);\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 def hello_rtdb(data, context):\n \"\"\"Triggered by a change to a Firebase RTDB reference.\n Args:\n data (dict): The event payload.\n context (google.cloud.functions.Context): Metadata for the event.\n \"\"\"\n trigger_resource = context.resource\n\n print(\"Function triggered by change to: %s\" % trigger_resource)\n print(\"Admin?: %s\" % data.get(\"admin\", False))\n print(\"Delta:\")\n print(json.dumps(data[\"delta\"]))\n\n### Ruby\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 require \"functions_framework\"\n\n # Triggered by a change to a Firebase RTDB document.\n FunctionsFramework.cloud_event \"hello_rtdb\" do |event|\n # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n # The Firebase event payload can be obtained from the `data` field.\n payload = event.data\n\n logger.info \"Function triggered by change to: #{event.source}\"\n logger.info \"Admin?: #{payload.fetch 'admin', false}\"\n logger.info \"Delta: #{payload['delta']}\"\n end\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)."]]