# Firebase Remote Config 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.

Cloud Run functions can be triggered in response to changes in
[Firebase Remote Config](https://firebase.google.com/docs/remote-config) in the
same Google Cloud project as the function. This makes it possible to change
the behavior and appearance of your app without publishing an app update.

## Event types

Firebase Remote Config can trigger functions in response to the
`remoteconfig.update` event.

| Event Type | Trigger |
|---|---|
| `remoteconfig.update` | Triggered when the remote config template is updated. |

## Event structure

Event data is provided as a transformed [`remoteConfig` object](https://firebase.google.com/docs/reference/remote-config/rest/v1/RemoteConfig).

For example:

```bash
{
  "updateType": "FORCED_UPDATE",
  "updateOrigin": "CONSOLE",
  "versionNumber": 1
}
```

## Sample code

### Node.js

```javascript
/**
 * Background Function triggered by a change to a Firebase Remote Config value.
 *
 * @param {object} event The Cloud Functions event.
 */
exports.helloRemoteConfig = event => {
  console.log(`Update type: ${event.updateType}`);
  console.log(`Origin: ${event.updateOrigin}`);
  console.log(`Version: ${event.versionNumber}`);
};
```

### Python

```python
def hello_remote_config(data, context):
    """Triggered by a change to a Firebase Remote Config value.
    Args:
           data (dict): The event payload.
           context (google.cloud.functions.Context): Metadata for the event.
    """
    print(f'Update type: {data["updateType"]}')
    print(f'Origin: {data["updateOrigin"]}')
    print(f'Version: {data["versionNumber"]}')

```

### Go

```go

// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"log"
)

// A RemoteConfigEvent is an event triggered by Firebase Remote Config.
type RemoteConfigEvent struct {
	UpdateOrigin string `json:"updateOrigin"`
	UpdateType   string `json:"updateType"`
	UpdateUser   struct {
		Email    string `json:"email"`
		ImageURL string `json:"imageUrl"`
		Name     string `json:"name"`
	} `json:"updateUser"`
	VersionNumber string `json:"versionNumber"`
}

// HelloRemoteConfig handles Firebase Remote Config events.
func HelloRemoteConfig(ctx context.Context, e RemoteConfigEvent) error {
	log.Printf("Update type: %v", e.UpdateType)
	log.Printf("Origin: %v", e.UpdateOrigin)
	log.Printf("Version: %v", e.VersionNumber)
	return nil
}
```

### Java

```java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.logging.Logger;

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

  // Use GSON (https://github.com/google/gson) to parse JSON content.
  private static final Gson gson = new Gson();

  @Override
  public void accept(String json, Context context) {
    JsonObject body = gson.fromJson(json, JsonObject.class);

    if (body != null) {
      if (body.has("updateType")) {
        logger.info("Update type: " + body.get("updateType").getAsString());
      }
      if (body.has("updateOrigin")) {
        logger.info("Origin: " + body.get("updateOrigin").getAsString());
      }
      if (body.has("versionNumber")) {
        logger.info("Version: " + body.get("versionNumber").getAsString());
      }
    }
  }
}
```

### C#

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

namespace FirebaseRemoteConfig;

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

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

    public Task HandleAsync(CloudEvent cloudEvent, RemoteConfigEventData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Update type: {origin}", data.UpdateType);
        _logger.LogInformation("Update origin: {origin}", data.UpdateOrigin);
        _logger.LogInformation("Version number: {version}", data.VersionNumber);

        // 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 change to a Firebase Remote Config value
FunctionsFramework.cloud_event "hello_remote_config" 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 Firebase event payload can be obtained from the event data.
  payload = event.data

  logger.info "Update type: #{payload['updateType']}"
  logger.info "Origin: #{payload['updateOrigin']}"
  logger.info "Version: #{payload['versionNumber']}"
end
```

### PHP

```php
use Google\CloudFunctions\CloudEvent;

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

    $data = $cloudevent->getData();

    fwrite($log, 'Update type: ' . $data['updateType'] . PHP_EOL);
    fwrite($log, 'Origin: ' . $data['updateOrigin'] . PHP_EOL);
    fwrite($log, 'Version: ' . $data['versionNumber'] . PHP_EOL);
}
```

### Deploying your function

To deploy your function, you need to specify the event type
`google.firebase.remoteconfig.update`.

The following `gcloud` command deploys a function that is triggered
by a Firebase Remote Config event:

```bash
gcloud functions deploy FUNCTION_NAME \
  --no-gen2 \
  --entry-point ENTRY_POINT \
  --trigger-event google.firebase.remoteconfig.update \
  --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 google.firebase.remoteconfig.update` | Trigger the function upon Firebase Remote Config update events. |
| `--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). |