Unable to authenticate against Firestore emulator - node.js

I'm using Firebase admin with Node + Express to update Firestore documents from Appengine. I have some tests that I want to have using the Firestore emulator. Here's the error I'm getting:
Error in post /requests Error: {"servicePath":"localhost","port":8080,
"clientConfig":{},"fallback":true,"sslCreds":{"callCredentials":{}},
"projectId":"test-project","firebaseVersion":"9.4.1","libName":"gccl",
"libVersion":"4.7.1 fire/9.4.1","ssl":false,
"customHeaders":{"Authorization":"Bearer owner"},"scopes":[
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"
]}
You need to pass auth instance to use gRPC-fallback client in browser. Use OAuth2Client from google-auth-library.
Before each test I'm calling:
var serviceAccount = require(process.env.FIREBASE_SA_CREDENTIAL);
firebaseAdmin.initializeApp({
credential: admin.credential.cert(serviceAccount),
projectId: 'test-project'
});
And the test is using a class that simply accesses Firestore like this:
this.db = firebaseAdmin.firestore();
...
I've got the following npm dependencies:
"#google-cloud/firestore": "^4.7.1",
"firebase": "^8.0.2",
"firebase-admin": "^9.4.1"
"firebase-tools": "^8.16.2"
I'm starting the emulators and running tests with:
firebase emulators:exec 'jest --verbose=false'
I can't see what's incorrect in the config - As far as I can see, the emulator should accept all auth. The error message suggests it's using some frontend library rather than a backend library, but the dependencies all appear to be correct.

OK, solved. There was an important line missing from jest config:
module.exports = {
testEnvironment: 'node'
}
testEnvironment: 'node'. This was triggering some behaviour in the Firebase libs that made them think the environment was a browser.

Related

Firebase not found while it is installed Shopify app

I am developing a Shopify app in which I intend to use Firebase as my storage, I successfully installed it and I see the package in package.json "firebase": "^9.5.0" but when importing I get this error in the terminal ERROR in ./conn.js ┃ Module not found: Error: Can't resolve 'firebase'
I tried the solutions in other similar questions but nothing worked, should I do something special to get Firebase working with Shopify?
Here is the code that I use the exact way in my React project and it works there
import firebase from 'firebase';
const firebaseApp = firebase.initializeApp({
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
measurementId: "XXX"
});
const db=firebaseApp.firestore();
export default db;
Please make sure to follow the steps as mentioned in the official documentation to Add Firebase to your JavaScript project.
As mentioned in this document, you should be importing as below, for your version 9 SDK:
import { initializeApp } from 'firebase/app';
However, if you are developing an app, you need to follow the guidelines from here:
Android - Add Firebase to your Android project
iOS+ - Add Firebase to your Apple project

Firebase error: Function failed on loading user code (node.js)

I am a relative noob with Firebase my first time using it and following along with a tutorial. The tutorial is a bit outdated and I have been fixing bugs as I have been going, but this one has got me completely stuck. I try to run a different functions that trigger when a document is created
in certain collections. However, i get the following error:
Error
! functions[createNotificationOnlike(us-central1)]: Deployment error.
Function failed on loading 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
There are 3 more identical errors that correspond to the other exports in the following index.js file.
Index.js
exports.createNotificationOnlike = functions.firestore.document('likes/{id}').onCreate(async (snapshot) => {
try {
const doc = await db.doc(`posts/${snapshot.data().postId}`).get(); // we have access to user handle via the likes route
if(doc.exists){
await db.doc(`notifications/${snapshot.id}`).set({ // the id of the like is the same as the id of the notification that pertains to the like
createdAt: new Date().toISOString,
recipient: doc.data.userHandle,
sender: snapshot.data().userHandle,
type: 'like',
read: false,
postId: doc.id
});
return;
}
} catch (err) {
console.error(err);
return;
}
});
exports.removeNotificationOnUnlikePost = functions.firestore.document('likes/{id}').onDelete( async (snapshot) => {
try {
await db.doc(`notifications/${snapshot.id}`).delete();
return;
} catch (err) {
console.error(err);
return;
}
})
exports.createNotificationForComments = functions.firestore.document('comments/{id}').onCreate(async (snapshot) => {
try {
const doc = await db.doc(`posts/${snapshot.data().postId}`).get();
if(doc.exists){
db.doc(`notifications/${snapshot.id}`).set({
createdAt: new Date().toISOString,
recipient: doc.data.userHandle,
sender: snapshot.data().userHandle,
type: 'comment',
read: false,
postId: doc.id
})
return;
}
} catch (err) {
console.error(err);
return; // we dont need return messages since this isnt an endpoint it is a db trigger event
}
})
// auto turn the app into base route url/api
exports.api = functions.https.onRequest(app);
I have checked the logs as suggested by the error and i get the following messages which i think are useless, there are three other identical errors for the other functions
Error Logs
removeNotificationOnUnlikePost
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading 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"}
Here is my package.json file
Package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"dependencies": {
"busboy": "^0.3.1",
"express": "^4.17.1",
"firebase": "^7.16.0",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Lastly, here is my config stuff that was used to initialize everything:
admin.js
const admin = require('firebase-admin');
var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: "socialapp-e5130.appspot.com",
databaseURL: "https://socialapp-e5130.firebaseio.com"
});
const db = admin.firestore();
module.exports = { db, admin }
Firebase init
const firebase = require('firebase');
const config = require('../util/config.js');
firebase.initializeApp(config);
P.S. It is worth mentioning that the http.onRequest trigger (api) was actually working and I have been developing without deploying using firebase serve. Now that I am ready to deploy these triggers something is going heinously wrong. Any help is greatly appreciated
Enter this command for getting log:
firebase functions:log
I had the exact same problem, trying to deploy the exact same code as you and I was just able to get it to deploy properly.
If yours is the same issue as mine, this is where the problem is:
var serviceAccount = require('../../service-acct/socialapp-e5130-firebase-adminsdk-uo6p6-5495e18b97.json');
It looks like when deploying to firebase you cant have code trying to reach outside your project folder, so the solution would be to have the key inside which isn't recommended or to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of your service account key json file as explained in https://firebase.google.com/docs/admin/setup#windows and then just having
admin.initializeApp();
I had the same issue while setting up SendGrid.
I got this error because I accidentally installed SendGrid to the root folder instead of the functions folder.
Make sure to install your service to your functions folder using the cmd prompt. It should look something like this:
D:\firebaseProject\functions> npm i #sendgrid/mail
I had this error once and I fixed it by checking my code again, check maybe you require or import a dependency or module that you have not installed and try to check your package.json file make sure you installed all the necessary module and dependencies.
But mostly the problem is due to importing a module you did not install or there is a bug in your code
in my case i had a file starting with capital case letter, but require(...) with a lower case letter, it worked on Mac because it ignores it, as i understand, but deploying these functions results in this error.
Renaming file to lower case fixed this error for me.
Mine was because I tried to import a module that dependents that is not standard-alone
const axioms = require("axioms");
I solved it by adding the module name version to dependencies list in the package.json file.
"dependencies": {
....
"axios": "^0.27.2"
}
I got the module version with this command
npm view axios version
With the suggestion of the recommended answer I moved all my cloud functions code to the single index.js file (rather than 'require' statements) and it seemed to work for me. Note that I omitted any API keys and such and it still worked. I am assuming that since this deployment is handled by the firebase CLI it already knows this is a trusted environment.
I had this same problem. check if your package.json file has all the dependencies that you used to write firebase functions.
e.g. I had written a firebase function in which I called nodemailer dependancy but did not installed in package.json file of 'functions' directory
Note: Remember to install required packages in 'functions' directory only
Another way to view deployment-time logs is to go to the Logs Explorer in the Google Cloud Console.
If you're not familiar with Google Cloud console, maybe because you're only familiar with the Firebase console that's a simplified version of the Google Cloud console, then check out these docs for how to access the Logs Explorer on Google Cloud Console.
In my case, I had to access the logs from the Logs Explorer because when I ran firebase functions:log as suggested by Chinmay Atrawalkar, I got the error Error: Failed to list log entries Failed to retrieve log entries from Google Cloud..
Through the Logs Explorer, I could see the following error: Detailed stack trace: Error: Cannot find module 'file-saver'. From there I was able to figure out I just needed to add file-saver to my functions/package.json dependencies by running yarn add file-saver from my functions directory.

firebase.database() is not a function on local node

I'm running a simple node app in my local machine and I need to connect to firebase realtime database.
I installed firebase via npm:
npm install firebase --save
Then I initialize the app:
var firebase = require("firebase");
var config = {
apiKey: "api-key",
authDomain: "my-app-database.firebaseapp.com",
databaseURL: "https://my-url.firebaseio.com",
storageBucket: "my-app-database.appspot.com",
};
firebase.initializeApp(config);
var myRef = firebase.database().ref("collection").on("value", (snap) => {
// do something with the data
});
Then I get the error that database is not a function. I check firebase.database and is undefined, also so are firebase.auth and firebase.storage.
I followed all the steps in the docs, but I don't see anything that could be causing this.
Goodness gracious... It was as simple as requiring the other packages in the file, like this:
// firebase
const firebase = require("firebase");
// get database, auth and storage
require("firebase/auth");
require("firebase/storage");
require("firebase/database");
Nowhere in the docs or reference says that. I thought about going back a version, perhaps 4.12.x, so I went to the npm page to see the previous versions and install one of those and try, when I found this:
https://www.npmjs.com/package/firebase#include-only-the-features-you-need
Just scroll down where they mention using npm packages or Typescript and you'll find the answer.
Shout out to the Firebase team, this information can't be just in the npm page and not in the docs, getting started guides or the github repo. Not a lot of people goes to the npm page of a package for information and I went there to check previous versions, so I kind of stumbled upon it.

Firebase Admin SDK initialization failed from TypeScript

I am trying to import the Firebase Admin SDK in my TypeScript (Nest.js) application.
let serviceAccount = require("../../creds.json");
console.log(serviceAccount);
const firebase = require("firebase");
firebase.initializeApp(environment.firebase);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "projectid"
});
But when I try and build the application I get the following error.
ERROR in ./node_modules/#google-cloud/firestore/src/v1beta1/firestore_client.js
Module not found: Error: Can't resolve './firestore_client_config' in '/home/jaybell/trellis-server/trellis/node_modules/#google-cloud/firestore/src/v1beta1'
# ./node_modules/#google-cloud/firestore/src/v1beta1/firestore_client.js 28:17-53
# ./node_modules/#google-cloud/firestore/src/v1beta1/index.js
# ./node_modules/#google-cloud/firestore/src/index.js
# ./src/server/main.server.ts
ERROR in ./node_modules/google-gax/lib/operations_client.js
Module not found: Error: Can't resolve './operations_client_config' in '/home/jaybell/trellis-server/trellis/node_modules/google-gax/lib'
# ./node_modules/google-gax/lib/operations_client.js 30:17-54
# ./node_modules/google-gax/index.js
# ./node_modules/#google-cloud/firestore/src/v1beta1/index.js
# ./node_modules/#google-cloud/firestore/src/index.js
# ./src/server/main.server.ts
ERROR in ./node_modules/google-gax/index.js
Module not found: Error: Can't resolve './package' in '/home/jaybell/trellis-server/trellis/node_modules/google-gax'
# ./node_modules/google-gax/index.js 65:18-38
# ./node_modules/#google-cloud/firestore/src/v1beta1/index.js
# ./node_modules/#google-cloud/firestore/src/index.js
# ./src/server/main.server.ts
I have tried to search up any connection between the admin sdk and the google-cloud firestore package but nothing has shown up. I tried to include the firestore library and initialize it as well but this error still shows up.
I included the admin sdk exactly as in the firebase docs with
import * as admin from 'firebase-admin';
after installing with
yarn add firebase-admin
I know the firebase admin sdk can communicate with firestore but unsure of why it would be throwing this error during initialization.
It might have something to do with my project including both a front end and back end component that are compiled together, Node server that serves an angular site. Could the firebase admin sdk be being compiled with the front end possibly causing this error?
Any thoughts?
Ok I think I may have solved my own problem.
The issue was was that the firebase-admin-sdk was being included in the build process and was causing it to fail.
Fix was:
install https://github.com/liady/webpack-node-externals
and add that to my webpack.config.ts file and exclude the node_modules folder.
I then had to authenticate through gcloud, instructions here:
Could not load the default credentials? (Node.js Google Compute Engine tutorial)
And now the build and serve works.
You lost add to webpack json extension for resolve
module.exports = {
...
resolve: {
extensions: ['.ts', '.js', '.json']
}
...
};

FireStore - TypeError: k.setTimeout is not a function

I'm using Firebase in a React Native app and authentication with a facebook token. It works fine with RealTime Database.
But not Firestore. When I call collection.get, set or add I got this error which is not caught by my handler but just dumped in the console.
(node:15795) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: k.setTimeout is not a function
I tried also as a standalone script run as node t_firebase.js.
I installed the packages with
npm install firebase
npm install firestore
I'm using node v6.11.4 and npm 3.10.10, firestore 1.1.6, firebase 4.5.1
Here is the script:
var firebase = require("firebase");
require("firebase/firestore");
var config = {
apiKey: "...",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
testFirebase();
function testFirebase(){
console.log("testFirebase");
token="...";
var credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential)
.then(function(val){testFirestore();})
.catch((error)=>{console.log("error:"+error);});
}
function testFirestore(){
console.log("testFirestore");
var db = firebase.firestore();
var collection = db.collection("livros");
var docref = collection.add({
autor: "AdaLovelace",
name: "blabla"
}).then(function(val){ console.log("OK"); }).catch((error)=>{console.log("error:"+error);});
}
Although you mention React Native, your error is actually from node.js so I'm not certain which environment you're asking about.
React Native - The "firebase" npm module does not currently work with React Native due to a bug. See https://github.com/firebase/firebase-js-sdk/issues/183 for more details and workarounds.
Node.JS - You can use Cloud Firestore from Node.JS using the "firebase-admin" SDK. See the node.js snippets on https://firebase.google.com/docs/firestore/quickstart for more details. Cloud Firestore is not currently supported via the "firebase" SDK, but this is planned in the future. See https://github.com/firebase/firebase-js-sdk/issues/221 for more details.

Resources