Initialising Algolia in Firebase Cloud functions - node.js

I am using the Algolia extension for Firebase. In Algolia I have an index with many docuemnts. Each user of my app should access only the documents they created. In order to implement this filter I need to generate a specific, filtered API key in Algolia for each user. I am trying to do this with a cloud function in Fireabse.
I get an error when I try to initialize Algolia in my local cloud functions index.js file and then deploy the functions.
Combining the docs of Cloud Functions and Algolia, I am doing this:
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
// For the default version
const algoliasearch = require('algoliasearch');
// For the default version
// import algoliasearch from 'algoliasearch';
// For the search only version
// import algoliasearch from 'algoliasearch/lite';
const client = algoliasearch('appId', 'AdminApiKey');
const index = client.initIndex('profiles');
I haven't written any Algolia function yet, so I know that the error comes from this initialisation. (My other non-Aloglia cloud functions are running fine). And the Algolia search function installed automatically as a Firebase extension works fine too.
This is the error I get in the terminal when trying to deploying the cloud functions:
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
Functions deploy had errors with the following functions:
writeToFirestore(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
Thank you for any help!

So in the end the problem was that I had not installed the algoliasearch package in the Firebase Cloud Functions directory but in the parent (root) directory of the app.

Related

What is the difference between Firebase SDK and Firebase SDK for cloud functions?

I don't understand the difference between Firebase SDK and Firebase SDK for cloud functions. I mean, when you run in command line "firebase init" in node.js, node modules will be downloaded to initialize a new project. But if i run "npm install firebase" different node modules appears, with similar names and different contents. So the question is: which SDK should I use to run functions and authentication in the same code? (I got a lot of require error from importing similar things and I don't know how to solve the problem).
Here is the code:
const functions = require('firebase-functions');
var firebase = require('firebase');
firebase.initializeApp();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
exports.delete = functions.https.onRequest((request, response) => {
console.log("delete");
});
The error says firebase.auth() is not a function, maybe for bad import and I don't know which package I need to import
npm install firebase installs modules to be used in client code that accesses Firebase products such as Firebase Authentication, Realtime Database, Firestore, and Cloud Storage.
npm install firebase-functions install modules to be used when writing backend code to deploy to Cloud Functions.
You're trying to use the Firebase Authentication client side library to listen to auth state changes in Cloud Functions. This isn't going to work, since that auth library only works on web clients.

Why is Google Cloud Functions throwing a "Invalid value for config firebase.databaseURL" error when I try to initialize a firebase app?

I have a Google Cloud Function that syncs presence information from a Firebase realtime database to a Firestore database (as explained here). This is the relevant Cloud Functions code from the linked example:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// Since this code will be running in the Cloud Functions enviornment
// we call initialize Firestore without any arguments because it
// detects authentication from the environment.
const firestore = admin.firestore();
// Create a new function which is triggered on changes to /status/{uid}
// Note: This is a Realtime Database trigger, *not* Cloud Firestore.
exports.onUserStatusChanged = functions.database.ref('/status/{uid}').onUpdate(
(change, context) => {
// Get the data written to Realtime Database
const eventStatus = change.after.val();
// Then use other event data to create a reference to the
// corresponding Firestore document.
const userStatusFirestoreRef = firestore.doc(`status/${context.params.uid}`);
// It is likely that the Realtime Database change that triggered
// this event has already been overwritten by a fast change in
// online / offline status, so we'll re-read the current data
// and compare the timestamps.
return change.after.ref.once('value').then((statusSnapshot) => {
const status = statusSnapshot.val();
console.log(status, eventStatus);
// If the current timestamp for this data is newer than
// the data that triggered this event, we exit this function.
if (status.last_changed > eventStatus.last_changed) {
return null;
}
// Otherwise, we convert the last_changed field to a Date
eventStatus.last_changed = new Date(eventStatus.last_changed);
// ... and write it to Firestore.
return userStatusFirestoreRef.set(eventStatus);
});
});
I recently received an email from Google informing me that I will need to update from NodeJS 6 to NodeJS 8 or 10. As this particular function isn't in production yet, I went ahead and made the configuration change in the Google Cloud Console. I now get the error below. I tried switching back to NodeJS 6, recreating the function from scratch, checking Github issues and other online forums. It appears that my Google Cloud Function is no longer being provided with the necessary environment variables to connect with Firebase/Firestore. However, I'm unsure why that would be the case.
Error: Invalid value for config firebase.databaseURL: undefined
at resourceGetter (/srv/node_modules/firebase-functions/lib/providers/database.js:101:19)
at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:102:13)
at /worker/worker.js:825:24
at <anonymous> at process._tickDomainCallback (internal/process/next_tick.js:229:7)
This error also shows up in the Stackdriver logs for the Cloud Function:
Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail
You should redeploy using the Firebase CLI. It does some special things in the environment to help the Firebase Admin SDK initialize correctly without any parameters (adding FIREBASE_CONFIG). It sounds like when you changed the runtime in the console, you also lost this special configuration.
For me, I use firestore, and I was getting the same error as you, so I had to create a real-time database without any record then I set the credentials for the admin like so:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
databaseURL: "your realtime database url"
});
When you are done, run firebase deploy --only functions to deploy your functions.
Here is your Realtime database URL:

Node.JS - firebase.auth() is not a function

I'm trying to use firebase Auth on a Node.JS server because Firebase Admin SDK doesn't implement all functions I need. Like firebase.auth.sendPasswordResetEmail(email).
But, when I try to get auth() I get following error:
let auth = fire.auth()
^
TypeError: fire.auth is not a function
My code is very simple:
let admin = require('firebase-admin');
let firebase = require('firebase');
const fire = firebase.initializeApp(config, "firebase");
let auth = fire.auth()
I'm, also, using Firebase Admin SDK for other functions and its auth() works fine.
There is some problem with use regular Firebase SDK on a Node.JS server?
EDIT:
I need both SDK because firebase-admin doesn't have functions like firebase.auth.sendPasswordResetEmail(email) or others.
Also, initializeApp is necessary for select the project in which I would operate.
Try deleting and re-installing node_modules. If the problem persists, you can add Firebase Authentication SDK to your script from the CDN:
<script src="https://www.gstatic.com/firebasejs/6.4.1/firebase-auth.js"></script>.
Refer here for the latest version: https://firebase.google.com/docs/web/setup

Google Firebase Web App - Error involving Cloud Functions and Firestore

Recently, I tried to follow a few demos online to get started on a Google Firebase Cloud Functions Node.js server-side code for an application. Upon attempting to add a Firebase App (and Firestore with it),
const functions = require('firebase-functions');
const firebase = require('firebase-admin');
require('firebase/firestore');
var serviceAccount = require("<private key>.json");
const initAppFirebase = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "<URL>"
});
var db = firebase.firestore();
I begin to get this one error that mentions a missing "annotations.proto" file from the google-gax module (which is apparently imported at some point in Firestore).
Error during trigger parsing: Error occurred while parsing your function
triggers.
Error: The include `google\api\annotations.proto` was not found.
at Function.GoogleProtoFilesRoot._findIncludePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:312:11)
at GoogleProtoFilesRoot.resolvePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:298:31)
...
at v1beta1 (C:\...\functions\node_modules\#google-
cloud\firestore\src\v1beta1\index.js:30:10)
at new Firestore (C:\...\functions\node_modules\#google-
cloud\firestore\src\index.js:229:18)
I have looked around on the internet, but nobody else seems to have this problem. I just reinstalled the files, but I am still getting this issue. Removing the Firestore and Firebase initializeApp code allows it to work, so I believe it has something to do with that.
Here are my module versions from package.json
"firebase-admin": "^5.12.0",
"firebase-functions": "^1.0.1",
"firestore": "^1.1.6",
Is there a way to fix this problem (botched installation, outdated libraries, missing code/requires etc.)? Thank you very much.
EDIT: Added code and package.json for version info. I dug around in the actual file \node_modules\google-gax\lib\grpc.js and found that it tries to return a valid path leading to the import file annotation.proto by trying to test google\api\annotations.proto at each parent directory.
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
There is, unfortunately, no such directory, though perhaps it is looking for the annotations file in google-proto-files\google\api\annotations.proto (but adding that file in manually leads to further errors). There is also a github issue here https://github.com/googleapis/nodejs-firestore/issues/175 mentioning it.
You say that you're trying to build a web app. But the code you are using is for initializing the Firebase Admin SDK in a (server-side) Node.js script.
If you want to use Firestore in your web app, start with the code you see when you click the WEB tab on this page:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-firestore.js"></script>
And then:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
You can get the values in that initializeApp call by:
Going to the Project overview page
Click ADD ANOTHER APP
Click Add Firebase to your web app

Firebase Node.js admin SDK timeouts when trying to access Realtime DB

Using the Node.js admin SDK with Firebase Functions I get a timeout whenever I try to access the Realtime Database. This occurs only when testing a function locally (firebase serve --only functions,hosting) and when the default app is initialized using the functions.config().firebase.
This is a new behavior that started just a couple a days ago. However, if I try to initialize the default app with the serviceAccount.json file everything works as expected.
I'm using firebase-admin version 4.2.1 and firebase-functions version 0.5.9.
I wrote a straight forward http triggered function that fails due to timeout:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.database();
exports.testDbConnection = functions.https.onRequest((req, res) => {
return admin.database().ref().once('value')
.then(function(snapshot) {
res.json(snapshot);
}).catch(function(error) {
res.json(error);
});
});
from the documentation
Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system
see https://firebase.google.com/docs/functions/http-events#terminate_http_functions
This might depend on the firebase-tools version that you are using, but looks familiar to this Github issue
The solution for it is to either upgrade to the latest version of the CLI or use the workaround solution:
Go to https://cloud.google.com/console/iam-admin/serviceaccounts
Click “Create service account”, give it a name (e.g. emulator), give it the Project>Owner role.Check “Furnish a new private key”, pick “JSON”.
Save the file somewhere on your computer
Run export GOOGLE_APPLICATION_CREDENTIALS="absolute/path/to/file.json"
Run firebase serve --only functions

Resources