Is it possible to have a Firebase Function that is triggered by changes to a Firestore that lives in a seperate Firebase project to the Function?

Viewed 811

Let's say I have a Firebase project named "A". Within this project, I have a Cloud Firestore triggered Firebase function that needs to run when a document within Firestore changes. By default, the Firebase Function will listen to changes within Firestore on project A.

However, let's say I have a particular use case where there is a second Firebase project named "B". I need the Firebase Function within Project A to be triggered on Firestore changes that happen to Firestore within project B.

Is this possible? Firebase docs do show initializing multiple projects, which would allow me to connect to multiple databases as such:

const admin = require("firebase-admin");
const serviceAccount = require("path/to/serviceAccountKey.json");

const secondaryAppConfig = {
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
};

// Initialize another app with a different config
const secondary = firebase.initializeApp(secondaryAppConfig, "secondary");

// Retrieve the database.
const secondaryDatabase = secondary.database();

But this doesn't allow me to trigger a Firestore Triggered Firebase Function on my secondary project. Firebase functions call the firebase-functions methods directly, whereas calling a database calls the initialized project.

const functions = require('firebase-functions');

exports.myFunction = functions.firestore
  .document('...')
  .onWrite((change, context) => { /* ... */ });

Is what I would like to do possible? Or does anyone have a workaround (other than creating this Firebase Function within project B)?

3 Answers

It's not possible. Cloud Functions triggers can only fire in response to changes in the resources of the project where they are deployed. This is true for all types of triggers, including Firestore.

If you want code to run in response to changes in another project, the function will have to be deploy to that project.

Currently it is only possible for writes to Cloud Firestore to trigger Cloud Functions that are part of the same project. It is not possible to trigger Cloud Functions that are defined in another project.

The typical solution is for example to call a HTTP Function in the secondary project, for which you can then configure the complete URL.

I'm not sure it can be done all in one codebase - that's from a lack of experience though. I'd say, given your setup, your calling function can trigger your callee function via HTTP call (documentation)

This might require a paid Firebase plan, but I'm not certain of it (source)

Related