# Google Analytics for Firebase Triggers

> [!WARNING]
>
> **Beta**
>
>
> This feature is covered by the
> [Pre-GA Offerings Terms](https://cloud.google.com/terms/service-terms#1) of the Google Cloud
> Terms of Service. Pre-GA features may have limited support, and changes
> to pre-GA features may not be compatible with other pre-GA versions.
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products#product-launch-stages).
>
>
> Specifically, note that
> [CloudEvents](https://docs.cloud.google.com/functions/1stgendocs/writing/write-event-driven-functions.md.txt) that are
> generated by Beta triggers may change format over time. The `Source`
> and `Subject` attributes, additional extension attributes, and the
> data (payload) format are all subject to change.

Google Analytics for Firebase provides event reports that help you
understand how users interact with your app. With Cloud Run functions, you
can access conversion events you have logged from Apple and Android devices
and trigger functions based on those events.

> [!WARNING]
> **Warning:** Only Apple platform and Android events marked as conversion events are supported by Cloud Run functions; Web conversion events are not available. You can specify which events are conversion events in the [Events tab](https://console.firebase.google.com/project/_/analytics/app/_/events) of the Firebase console **Analytics** pane.

> [!NOTE]
> **Note:** Unlike most other Cloud Run functions events, Google Analytics for Firebase events are not real-time and may be delayed. See [this blog post](https://firebase.googleblog.com/2016/11/how-long-does-it-take-for-my-firebase-analytics-data-to-show-up.html) for more information.

## Event types

Google Analytics for Firebase triggers the `log` event. This is
a powerful event type, since any action that a user takes in your app can be
logged and in turn trigger a function.

| Event Type | Trigger |
|---|---|
| `providers/google.firebase.analytics/eventTypes/event.log` | Triggered when a conversion event is logged. |

Cloud Run functions can respond to the logging of a Google Analytics for
Firebase conversion event. For instance, if a user makes an in-app purchase, an
`in_app_purchase` conversion event is logged and can be consumed by
Cloud Run functions.

## Event structure

This trigger invokes your function with an event similar to the one shown below:

```json
{
    "eventDim": [ // Contains a single event
        {
            "date": "20090213",
            "name": "screen_view",
            "params": {
                "firebase_conversion": {
                    "intValue": "1"
                },
                "firebase_event_origin": {
                    "stringValue": "auto"
                },
                "firebase_previous_class": {
                    "stringValue": "MainActivity"
                },
                "firebase_previous_id": {
                    "intValue": "1928209043426257906"
                },
                "firebase_previous_screen": {
                    "stringValue": "id-D-D"
                },
                "firebase_screen": {
                    "stringValue": "id-C-C"
                },
                "firebase_screen_class": {
                    "stringValue": "MainActivity"
                },
                "firebase_screen_id": {
                    "intValue": "1234567890000"
                }
            },
            "previousTimestampMicros": "1234567890000",
            "timestampMicros": "1234567890000"
        }
    ],
    "userDim": {
        // A UserDimensions object
    }
}
```

User information such as application information or device information can be
found in the `userDim` property. Information about the logged
event can be found in the `eventDim` array. The objects contained in that array
include a `name` field that holds the conversion event name (such as
`in_app_purchase`). Custom fields set up in Google Analytics for Firebase
also appear here.

## Code sample

Use the following snippet to process this response:

### Node.js

    /**
     * Background Function triggered by a Google Analytics for Firebase log event.
     *
     * @param {!Object} event The Cloud Functions event.
     */
    exports.helloAnalytics = event => {
      const {resource} = event;
      console.log(`Function triggered by the following event: ${resource}`);

      const [analyticsEvent] = event.data.eventDim;
      console.log(`Name: ${analyticsEvent.name}`);
      console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`);

      const userObj = event.data.userDim;
      console.log(`Device Model: ${userObj.deviceInfo.deviceModel}`);
      console.log(`Location: ${userObj.geoInfo.city}, ${userObj.geoInfo.country}`);
    };

### Python

```python
from datetime import datetime

def hello_analytics(data, context):
    """Triggered by a Google Analytics for Firebase log event.
    Args:
           data (dict): The event payload.
           context (google.cloud.functions.Context): Metadata for the event.
    """
    trigger_resource = context.resource
    print(f"Function triggered by the following event: {trigger_resource}")

    event = data["eventDim"][0]
    print(f'Name: {event["name"]}')

    event_timestamp = int(event["timestampMicros"][:-6])
    print(f"Timestamp: {datetime.utcfromtimestamp(event_timestamp)}")

    user_obj = data["userDim"]
    print(f'Device Model: {user_obj["deviceInfo"]["deviceModel"]}')

    geo_info = user_obj["geoInfo"]
    print(f'Location: {geo_info["city"]}, {geo_info["country"]}')

```

### Go

```go

// Package p contains a Google Analytics for Firebase Cloud Function.
package p

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/functions/metadata"
)

// AnalyticsEvent is the payload of an Analytics log event.
type AnalyticsEvent struct {
	EventDimensions []EventDimensions `json:"eventDim"`
	UserDimensions  interface{}       `json:"userDim"`
}

// EventDimensions holds Analytics event dimensions.
type EventDimensions struct {
	Name                    string      `json:"name"`
	Date                    string      `json:"date"`
	TimestampMicros         string      `json:"timestampMicros"`
	PreviousTimestampMicros string      `json:"previousTimestampMicros"`
	Params                  interface{} `json:"params"`
}

// HelloAnalytics handles Firebase Mobile Analytics log events.
func HelloAnalytics(ctx context.Context, e AnalyticsEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %w", err)
	}
	log.Printf("Function triggered by Google Analytics event: %v", meta.Resource)
	log.Printf("%+v", e)
	return nil
}
```

### C#

```c#
using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Firebase.Analytics.V1;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseAnalytics;

public class Function : ICloudEventFunction<AnalyticsLogData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, AnalyticsLogData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Event source: {source}", cloudEvent.Source);
        _logger.LogInformation("Event count: {count}", data.EventDim.Count);

        var firstEvent = data.EventDim.FirstOrDefault();
        if (firstEvent is object)
        {
            _logger.LogInformation("First event name: {name}", firstEvent.Name);
            DateTimeOffset timestamp = DateTimeOffset.FromUnixTimeMilliseconds(firstEvent.TimestampMicros / 1000);
            _logger.LogInformation("First event timestamp: {timestamp:u}", timestamp);
        }

        var userObject = data.UserDim;
        if (userObject is object)
        {
            _logger.LogInformation("Device model: {device}", userObject.DeviceInfo?.DeviceModel);
            _logger.LogInformation("Location: {city}, {country}", userObject.GeoInfo?.City, userObject.GeoInfo.Country);
        }
        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }
}
```

### Ruby

```ruby
require "functions_framework"

# Triggered by a Google Analytics for Firebase log event.
FunctionsFramework.cloud_event "hello_analytics" do |event|
  # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  # The Analytics event payload can be obtained from the `data` field.
  payload = event.data

  logger.info "Function triggered by the following event: #{event.source}"

  event = payload["eventDim"].first
  logger.info "Name: #{event['name']}"

  event_timestamp = Time.at(event["timestampMicros"].to_i / 1_000_000).utc
  logger.info "Timestamp: #{event_timestamp.strftime '%Y-%m-%dT%H:%M:%SZ'}"

  user_obj = payload["userDim"]
  logger.info "Device Model: #{user_obj['deviceInfo']['deviceModel']}"

  geo_info = user_obj["geoInfo"]
  logger.info "Location: #{geo_info['city']}, #{geo_info['country']}"
end
```

### PHP

```php
use Google\CloudFunctions\CloudEvent;

function firebaseAnalytics(CloudEvent $cloudevent): void
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $data = $cloudevent->getData();

    fwrite($log, 'Function triggered by the following event:' . $data['resource'] . PHP_EOL);

    $analyticsEvent = $data['eventDim'][0];
    $unixTime = $analyticsEvent['timestampMicros'] / 1000;

    fwrite($log, 'Name: ' . $analyticsEvent['name'] . PHP_EOL);
    fwrite($log, 'Timestamp: ' . gmdate("Y-m-d\TH:i:s\Z", $unixTime) . PHP_EOL);

    $userObj = $data['userDim'];
    fwrite($log, sprintf(
        'Location: %s, %s' . PHP_EOL,
        $userObj['geoInfo']['city'],
        $userObj['geoInfo']['country']
    ));

    fwrite($log, 'Device Model: %s' . $userObj['deviceInfo']['deviceModel'] . PHP_EOL);
}
```

## Deploying your function

To deploy your function, specify the event type and the project in which you
have Firebase Auth configured. In the console, there is a field for **Event
Type** which contains `log`---the only option---and **Log Event Name**, which is the
conversion event that will trigger the function.

On the command line, specific strings must be used to specify these parameters.
The following Google Cloud CLI command deploys a function that triggers when a
user makes an in-app purchase:

```bash
gcloud functions deploy FUNCTION_NAME \
  --no-gen2 \
  --entry-point ENTRY_POINT \
  --trigger-event providers/google.firebase.analytics/eventTypes/event.log \
  --trigger-resource projects/YOUR_PROJECT_ID/events/in_app_purchase \
  --runtime RUNTIME
```

> [!NOTE]
> **Note:** When you deploy a function using the Google Cloud CLI, the command must include the name of the function contained in your code that you want the `deploy` command to execute. You can specify that function using either `FUNCTION_NAME` or the optional `--entry-point` flag, depending on the needs of your implementation. See the [deployment guide](https://docs.cloud.google.com/functions/1stgendocs/deploy.md.txt#basics) for more discussion.

| Argument | Description |
|---|---|
| `FUNCTION_NAME` | The registered name of the Cloud Run function you are deploying. This can either be the name of a function in your source code, or an arbitrary string. If <var translate="no">FUNCTION_NAME</var> is an arbitrary string, then you must include the `--entry-point` flag. |
| `--entry-point ENTRY_POINT` | The name of a function or class in your source code. Optional, unless you did not use `FUNCTION_NAME` to specify the function in your source code to be executed during deployment. In that case, you must use `--entry-point` to supply the name of the executable function. |
| `--trigger-event NAME` | The name of the event type that the function wishes to receive. For Google Analytics for Firebase, this is always `providers/google.firebase.analytics/eventTypes/event.log.` |
| `--trigger-resource NAME` | The fully qualified Google Analytics event name, including your project information. This should take the form: `projects/YOUR_PROJECT_ID/events/CONVERSION_EVENT_NAME` |
| `--runtime RUNTIME` | The name of the runtime you are using. For a complete list, see the [`gcloud` reference](https://docs.cloud.google.com/sdk/gcloud/reference/functions/deploy.md.txt#--runtime). |