Implement callable cloud functions in Firebase client app - firebase

I have recently discovered the Firebase callable functions which allows me to call HTTPS trigger like function from the client side (and with auth() support).
I struggle to implement this new feature in my already existing Firebase web-client application.
I have some cloud functions running, among them are some HTTPS functions I would like to transform into an HTTPS callable function (with functions.https.onCall).
The documentation indicates:
Set up your client development environment
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-functions.js"></script>
And my code is:
import firebase from 'firebase';
import 'firebase/firestore';
const firebaseApp = firebase.initializeApp({
apiKey: '....',
authDomain: '....',
databaseURL: '....',
projectId: '....',
storageBucket: '....',
messagingSenderId: '....',
});
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
When I run my app, I got the following error:
Uncaught TypeError: firebaseApp.functions is not a function
I have tried yarn add firebase-functions and then import 'firebase-functions but then the app requires firebase-admin. I am affraid it is too much for a client-app so I might go in the wrong direction.
Can someone help me with this issue?
(!) This issue is NOT about the server-side Firebase SDK for Cloud Functions (Node JS). It is about calling Cloud functions directly from a Firebase web app.
Thank you!
UPDATE:
Thanks to #Andrew's post, this solves my issue:
My configuration
import firebase from 'firebase';
import 'firebase/firestore';
import '#firebase/functions';
import firestoreConfig from '#/config/firestore';
const firebaseApp = firebase.initializeApp(firestoreConfig /* The JSON configuration from my Firebase project */);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
Using the configuration:
import { db, functions } from '#/database/firestoreInit';
export default {
addMessage(text) {
const addMessage = functions.httpsCallable('addMessage');
return addMessage({ text }).then(result => result);
},
}

I just ran into this same problem myself and solved it by installing and importing the #firebase/functions npm package. I found the solution on github here:
https://github.com/firebase/firebase-js-sdk/blob/master/packages/functions/README.md
From the README on github:
ES Modules
import firebase from '#firebase/app';
import '#firebase/functions'
// Do stuff w/ `firebase` and `firebase.functions`
CommonJS Modules
const firebase = require('#firebase/app').default;
require('#firebase/functions');
// Do stuff with `firebase` and `firebase.functions`
Hope that helps! The actual documentation is not very clear about having to do this in order to call the functions.

About #firebase/functions:
This package is not intended for direct usage, and should only be used via the officially supported firebase package.
This worked for me:
import * as firebase from 'firebase/app'; // Typescript
// import firebase from 'firebase/app'; // JS
import 'firebase/functions';
const myCallableFunc = firebase.functions().httpsCallable('myCallableFunc');
I don't know about importing firebase-functions with a CDN but if you're using npm then you don't need the firebase-functions package, just installing firebase will do.

Follow the steps mentioned here. Firebase cloud functions
I think there is nothing like firebaseApp.functions.

Related

WebConfig doesn't return measurementId

I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.

'Firebase' connection problem, Same code worked in 'react JS' but not worked in 'react native' projects?

firebase-config.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "**********************************",
authDomain: "***********.firebaseapp.com",
projectId: "***********",
storageBucket: "***********.appspot.com",
messagingSenderId: "*************",
appId: "******************************",
measurementId: "****************",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
package.json
{
"firebase": "^9.4.0", // latest version
}
It gives this error when running the app
ERROR [2021-11-16T08:33:02.823Z] #firebase/firestore: Firestore (9.4.0): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
How to solve this error?
For react native.
Consider [https://rnfirebase.io/]. This will help you how to install Firebase in react native. As React Native is a cross platform and runs on native dom therefore you need to link the libraries and also add your bundle and package id in firebase console.
Again DONT WORRY, this link will help you to do everything easily.

VueJS and Firebase - import firebase package the correct way

I struggle with the correct import of the firebase SDK. I use Vue3 and installed firebase via yarn add firebase
This is my firebase.js file:
import firebase from 'firebase/app';
However, this results in the following error: 1:1 error 'firebase/app' should be listed in the project's dependencies. Run 'npm i -S firebase/app' to add it import/no-extraneous-dependencies
import firebase from 'firebase';
This works, but I get the follwing warning:
It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
So, first way seems to be recommended, but it does not work out for me. What am I doing wrong?
Update: This seems to be fixed in v2.23.4 (eslint-plugin-import).
Original answer: You're not doing anything wrong. This is a bug, probably related to the package definition in firebase, but it's discussed here inside the eslint rule's repo: https://github.com/benmosher/eslint-plugin-import/issues/2065
You either can use a comment to stop the error from occurring like so:
// eslint-disable-next-line import/no-extraneous-dependencies
import firebase from 'firebase/app';
Or you'll have to wait for the issue to be resolved. Downgrading to v2.22.1 of eslint-plugin-import might also work.
You need to create a config file for firebase and importing firebase here. Then, you
register the module you need and exported it so other file can use it as well.
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import "firebase/storage";
const firebaseConfig = {
// you can get this from your firebase console.
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
// init firebase
firebase.initializeApp(firebaseConfig);
// init services
const projectFirestore = firebase.firestore();
const projectAuth = firebase.auth();
const projectStorage = firebase.storage();
export { projectFirestore, projectAuth, projectStorage };
On your other file where you want to use your firebase, you could do something like this to import it.
import { projectAuth } from '../firebase/config'
const user = ref(projectAuth.currentUser)

How do I wire up the firestore emulator with my firebase functions tests?

Currently we are using 'firebase-functions-test' in online mode to test our firebase functions (as described here https://firebase.google.com/docs/functions/unit-testing), which we setup like so:
//setupTests.ts
import * as admin from 'firebase-admin';
const serviceAccount = require('./../test-service-account.json');
export const testEnv = require('firebase-functions-test')({
projectId: 'projectId',
credential: admin.credential.cert(serviceAccount),
storageBucket: 'projectId.appspot.com'
});
const testConfig = {
dropbox: {
token: 'dropboxToken',
working_dir: 'someFolder'
}
};
testEnv.mockConfig(testConfig);
// ensure default firebase app exists:
try {
admin.initializeApp();
} catch (e) {}
We would like to move away from testing against an actual firestore instance in our tests, and use the emulator instead.
The docs, issues, and examples I've been able to find on the net are either outdated, or describe how to set up the emulator for testing security rules, or the web frontend.
Attempts using firebase.initializeAdminApp({ projectId: "my-test-project" }); did not do the trick.
I also tried setting FIRESTORE_EMULATOR_HOST=[::1]:8080,127.0.0.1:8080
So the question is: How can I initialise the firebaseApp in my tests, so that my functions are wired up to the firestore emulator?
I had another crack at it today, more than a year later, so some things have changed, which I can't all list out. Here is what worked for me:
1. Install and run the most recent version of firebase-tools and emulators:
$ npm i -g firebase-tools // v9.2.0 as of now
$ firebase init emulators
# You will be asked which emulators you want to install.
# For my purposes, I found the firestore and auth emulators to be sufficient
$ firebase -P <project-id> emulators:start --only firestore,auth
Take note of the ports at which your emulators are available:
2. Testsetup
The purpose of this file is to serve as a setup for tests which rely on emulators. This is where we let our app know where to find the emulators.
// setupFunctions.ts
import * as admin from 'firebase-admin';
// firebase automatically picks up on these environment variables:
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099';
admin.initializeApp({
projectId: 'project-id',
credential: admin.credential.applicationDefault()
});
export const testEnv = require('firebase-functions-test')();
3. Testing a simple function
For this, we setup a simple script which writes a document to firestore. In the test, we assert that the document exists within the emulator, only after we have run the function.
// myFunction.ts
import * as functions from 'firebase-functions';
import {firestore} from 'firebase-admin';
export const myFunction = functions
.region('europe-west1')
.runWith({timeoutSeconds: 540, memory: '2GB'})
.https.onCall(async () => {
await firestore()
.collection('myCollection')
.doc('someDoc')
.set({hello: 'world'});
return {result: 'success'};
});
// myTest.ts
// import testEnv first, to ensure that emulators are wired up
import {testEnv} from './setupFunctions';
import {myFunction} from './myFunction';
import * as admin from 'firebase-admin';
// wrap the function
const testee = testEnv.wrap(myFunction);
describe('myFunction', () => {
it('should add hello world doc', async () => {
// ensure doc does not exist before test
await admin
.firestore()
.doc('myCollection/someDoc')
.delete()
// run the function under test
const result = await testee();
// assertions
expect(result).toEqual({result: 'success'});
const doc = await admin
.firestore()
.doc('myCollection/someDoc')
.get();
expect(doc.data()).toEqual({hello: 'world'});
});
});
And sure enough, after running the tests, I can observe that the data is present in the firestore emulator. Visit http://localhost:4000/firestore while the emulator is running to get this view.

Can not access to firebase.database.ServerValue.TIMESTAMP in React-Native

After upgraded to Firebase 3.2.0 (react-native 0.30), I'm trying to set a TIMESTAMP as described in the docs:
import Firebase from 'firebase'
...
let config = {
apiKey: `${ Config.firebase.apiKey }`,
authDomain: `${ Config.firebase.authDomain }`,
databaseURL: `${ Config.firebase.databaseURL }`,
storageBucket: `${ Config.firebase.storageBucket }`
}
const firebase = Firebase.initializeApp(config)
const created_at = firebase.database.ServerValue.TIMESTAMP
then I get
created_at = undefined
when debugging with Chrome' Developer Tools, firebase.database is a function without any ServerValue in it.
Any idea ?
Try this syntax:
import Firebase from 'firebase'
and then:
Firebase.database.ServerValue.TIMESTAMP
This works for me
import RNFirebase from "react-native-firebase"
data.timestamp = RNFirebase.database.ServerValue.TIMESTAMP;
In my case, even though I was using Firestore for all my data storage/retrieval using the web JS client, I had to import the Firebase Database libary at the start of my HTML like so
<script defer src="/__/firebase/7.17.1/firebase-database.js"></script>
Simply having <script defer src="/__/firebase/7.17.1/firebase-firestore.js"></script> is not enough. After loading the database module, then I could access firebase.database stuff, like ServerValue.TIMESTAMP
In my case, since I am using Firestore, then I used firebase.firestore.Timestamp.now() instead of the firebase.database bits above.

Resources