How to use Firebase Cloud Functions with the new modular Firestore API?

Viewed 97

I have upgraded my Firebase v8 project to v9. The web application now uses the modular SDK with the new functional API for Firestore.

In this project I use Firebase Functions. There I have upgraded to firebase-admin 11.0.0. But it seams it does not provide the new functional API for Firestore.

const { initializeApp } = require('firebase-admin/app');
const app = initializeApp();

import { getFirestore } from "firebase/firestore";
const db = getFirestore(app);

This throws:

TypeError: Cannot read properties of undefined (reading 'getProvider')
  at Object._getProvider (/p/happygast/node_modules/@firebase/app/src/internal.ts:110:6)
  at Object.getFirestore (/p/happygast/node_modules/@firebase/firestore/src/api/database.ts:185:10)

Now I am not sure if I am doing something wrong? Or is there no functional Firestore API for Cloud Functions?

In essence: Is firebase-admin/app compatible with firebase/firestore? Or: How do I initialize and use firebase/firestore in Firebase Cloud Functions?

1 Answers

You are importing initializeApp() from the Firebase Admin SDK but getFirestore() from the Firebase Client SDK and then passing an instance of Admin SDK in it that's invalid. Instead, you should import Firestore from the Admin SDK itself as shown below:

const { initializeApp } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore'); // not firebase/firestore

// Initialize by ADC or another service account 
const app = initializeApp();

const db = getFirestore(app);

If you want to use the client SDK, then you'll have to initialise the Firebase instance using the client SDK itself:

const { initializeApp } = require('firebase/app');
const { getFirestore } = require('firebase/firestore');

// use the web config that can be found in Firebase console
const clientApp = initializeApp({ ...config }); 

cpmst db = getFirestore(clientApp); 

Related