Listen to Firebase Realtime Database changes

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

Go

To authenticate to Cloud Run functions, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// Package rtdb contains a Cloud Function triggered by a Firebase Realtime Database
// event.
package rtdb

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/firebase/databasedata"
	"google.golang.org/protobuf/encoding/protojson"
)

func init() {
	functions.CloudEvent("HelloRTDB", HelloRTDB)
}

// HelloRTDB handles changes to a Firebase RTDB.
func HelloRTDB(ctx context.Context, e event.Event) error {
	unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true}

	var data databasedata.ReferenceEventData
	if err := unmarshalOptions.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("Unmarshal: %w", err)
	}
	log.Printf("Function triggered by change to: %v", e.Source())
	log.Printf("Data: %+v", data.GetData())
	log.Printf("Delta: %+v", data.GetDelta())
	return nil
}

Java

To authenticate to Cloud Run functions, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.firebase.database.v1.ReferenceEventData;
import com.google.protobuf.util.JsonFormat;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class FirebaseRtdb implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseRtdb.class.getName());

  @Override
  public void accept(CloudEvent event) throws Exception {
    if (event.getData() == null) {
      logger.info("No data found in event");
      return;
    }

    ReferenceEventData.Builder builder = ReferenceEventData.newBuilder();
    JsonFormat.Parser jsonParser = JsonFormat.parser().ignoringUnknownFields();
    jsonParser.merge(new String(event.getData().toBytes(), StandardCharsets.UTF_8), builder);
    ReferenceEventData data = builder.build();

    logger.info("Function triggered by change to: " + event.getSource().toString());

    if (data.hasDelta()) {
      logger.info("Delta: " + data.getDelta().toString());
    }

    if (data.hasData()) {
      logger.info("Data: " + data.getData().toString());
    }
  }
}

Node.js

To authenticate to Cloud Run functions, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * Cloud Event Function triggered by a change to a Firebase RTDB reference.
 *
 * @param {!Object} event The Cloud Functions event.
 */
const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('helloRTDB', event => {
  console.log(`Function triggered by change to: ${event.source}`);
  console.log('Data:');
  console.log(JSON.stringify(event.data.data, null, 2));
  console.log('Delta:');
  console.log(JSON.stringify(event.data.delta, null, 2));
});

Python

To authenticate to Cloud Run functions, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import json

from cloudevents.http import CloudEvent
import functions_framework


@functions_framework.cloud_event
def hello_rtdb(event: CloudEvent) -> None:
    """Triggered by a change to a Firebase RTDB reference.
    Args:
        event: Cloud Event triggered by change to Firebase Real Time Database.
    """
    print(f"Function triggered by change to: {event['source']}")
    print("Data:")
    print(json.dumps(event.data["data"]))
    print("Delta:")
    print(json.dumps(event.data["delta"]))

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.