Can't find variable: IDBIndex on firebase/react native(expo) - firebase

I am developing a RN app in Expo with firebase as backend. So far, the app only uses firebase auth and firestore and for whatever reason, I randomly started getting the error of ReferenceError: Can't find variable: IDBIndex. I adjusted my firebase config to suit the v9 standards instead of using the compat package. I ensured my app was not using Google Analytics. I have also downgraded to firebase#9.1.0 which matches up with the expo documentation and this other similar post.
I have also git reverted into previous versions of the app (with earlier dependencies and code) when it was working but still got back the same error. When this occurred, I entirely reinstalled node and npm because I thought that was the only other possible reason this could be happening but that was to no avail as well (getting the same IDB error). I still think this is a firebase related issue, but I am pretty much all out of ideas as to what it could be.
Here is my firebase config:
import { initializeApp } from 'firebase/app'
import { getAuth, connectAuthEmulator } from "firebase/auth";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import {
FIREBASE_API_KEY,
FIREBASE_AUTH_DOMAIN,
FIREBASE_PROJECT_ID,
FIREBASE_STORAGE_BUCKET,
FIREBASE_MESSAGING_SENDER_ID,
FIREBASE_APP_ID,
FIREBASE_MEASUREMENT_ID,
} from '#env';
const firebaseConfig = {
apiKey: FIREBASE_API_KEY,
authDomain: FIREBASE_AUTH_DOMAIN,
projectId: FIREBASE_PROJECT_ID,
storageBucket: FIREBASE_STORAGE_BUCKET,
messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
appId: FIREBASE_APP_ID,
measurementId: FIREBASE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
export default app;
export const auth = getAuth(app);
export const firestore = getFirestore(app);
if (process.env.NODE_ENV === "development") {
connectAuthEmulator(auth, "http://localhost:9099");
connectFirestoreEmulator(firestore, "localhost", 8080);
}
Do let me know if you need to see more files or need to know more details.

firebaser here
There was a problem in our JavaScript SDKs, where Firebase Installation Services used a version of IDB that doesn't support ESM outside of browser environments. The issue has been fixed in version 9.6.9 of the JavaScript SDK, so be sure to update to that.

I'm getting the same issue, looks like, it's breaking on "firebase": "^9.6.8", which was released a few days ago. Use "firebase": "9.6.7",

I've been getting the same issue, I've tried all the same things as you to no avail. I symbolicated the logs from firebase test lab and came up with this:
Stacktrace
Generally I have no idea how all of these libraries work together, but are you using typesense with firestore? I wonder if your stack trace calls out the same files, but I can't find any smoking gun here. I'll keep updating this thread if I find something. (I would have commented but I don't have the rep yet)
Update: Looks like my build just fixed itself somehow, even submitting builds from this weekend that would constantly crash. So truly I'm not sure what happened but it may be resolved

I had the same issue, my solution was to downgrade the Firebase version from 9.6.8 to 8.2.3.
Here is a reference that could be helpful.
https://github.com/expo/expo-cli/issues/3066

I had this same issue, and after trying multiple different firebase versions, this is the one that fixed the error for me:
npm install firebase#9.4.1 --save
Here's where I found this: Get Started with Cloud Firestore

The other fixes mentioned in this thread are definitely all valid (I have seen other forum posts suggesting the firebase downgrade but in my case it did not work.)
I thought it could be helpful for me to confirm what fixed the problem in my case. The problem arose from when one of my team members used npm instead of expo (which defaults to yarn) to install a dependency. This caused syncing issues between the yarn.lock and package-lock.json. This alone wouldn't have caused much of an issue because a simple yarn or yarn install <dependency> would have solved the issue. However, this dependency happened to require pre-existing dependencies which were of a different version then the ones "expected" by my version of expo. How this IDBIndex error was triggered is still a mystery to me, but in the end all I had to do was remove all my lock files and node_modules, perform an expo updateand finally do a yarn to reinstall all now-compatible packages.
If anyone stumbling across this answer can give a possible explanation as to why this fixed things, that would be much appreciated.

Here is what worked for me (using yarn):
deleted node_modules
deleted yarn.lock
downgraded to firebase "9.6.7" yarn add firebase#9.6.7
downloaded packages using yarn install
made sure all my imports are from the correct firebase library. I am using expo, and I had imported both firebase and react-native-firebase, which was causing trouble. I deleted react-native-firebase for now until I eject if needed.
Fixed my imports. Now you import firebase like this import firebase from "firebase/compat"

if you use firebase analytics, remove it
firebase version "firebase": "9.6.7"
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
// import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: process.env.FIREBASE_APP_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
export const app = initializeApp(firebaseConfig);
// export const analytics = getAnalytics(app);
export const firestore = getFirestore(app);

Had the same issue, I just downgraded firebase version and it worked.
you can use this code for downgrading:
npm install firebase#9.4.1 --save

This worked for Expo:
https://github.com/firebase/firebase-js-sdk/issues/6253#issuecomment-1123923581
// metro.config.js
const { getDefaultConfig } = require("#expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;

Related

this._firestore.native.x is not a function. react-native-firebase with expo

I'm using expo 44 to develop an app with firebase, to achieve that I'm using the react-native-firebase module that seems to be compatible with expo.
I followed the integration guide
I installed every required package at the last version available:
"#react-native-firebase/app": "^14.7.0",
"#react-native-firebase/auth": "^14.7.0",
"#react-native-firebase/firestore": "^14.7.0",
I added the plugin #react-native-firebase/app into app.json and ran expo prebuild --clean to generate custom code from plugins
I then built a development build on eas and deployed it to the iOS simulator (i also tested with android but didn't change anything)
The auth module works fine, which means that the integration with firebase when well but when running any firestore query or any firestore operation i get this error:
this._firestore.native.documentSet is not a function. (In 'this._firestore.native.documentSet(this.path, (0, _serialize.buildNativeMap)(data, this._firestore._settings.ignoreUndefinedProperties), setOptions)', 'this._firestore.native.documentSet' is undefined)
The way I'm importing firestore is by exporting it from this file firestore.ts
import firebase from "#react-native-firebase/app";
import "#react-native-firebase/firestore";
export default firebase.firestore();
This is the code I used to test:
const signInAnonymously = async () => {
try {
const user = await auth.signInAnonymously(); // This works fine
...
await firestore.collection("users").add({ a: "a" }); // Here I get the error
} catch (error) {
...
}
};

Emulator Storage running but ignored

I have a firebase function that is successfully uploading a file when run in the emulator, but the file ends up on production even though I'm running the Storage Emulator
I'm running with the following package.json snippets in the functions directory
"dependencies": {
"firebase-admin": "^8.13.0",
"firebase-functions": "^3.16.0",
...
}
"engines": {
"node": "14"
}
I'm initializing everything with defaults (which has worked fine in emulation and production until recently).
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const storage = admin.storage();
const bucket = storage.bucket();
...
const myFunction = async () => {
const savedFile = await bucket.file(`99999999.html`).save(fileContents);
}
The code above works, although the file ends up on production, not in the emulator storage. The logs show that a production google api is being accessed.
This would be fine (not ideal, but workable) if I could also read the file. But when I try to run the .exits() or .download() function for the same file with bucket.file('99999999.html').download();, I get the following log entries:
I need to either:
Get emulation for storage working to resolve this (ideal)
Figure out why downloading isn't working in this case
If anyone can help me with either, I'd greatly appreciate it.
I have updated firebase-admin and firebase-tools packages accordingly:
"dependencies": {
"firebase-admin": "^10.0.0",
"firebase-tools": "^9.23.1",
...
}
This resulted in a more clear error saying that the file downloaded did not match the file on the server (a hash mismatch from what I understand). I know that this is not the case, so I changed .download() to .download({validation: false}). This resolved my issue with accessing the file. It is still not storing on local emulation, but maybe that's not the intent.
UPDATE: I figured out you have to change the bucket to see your files in emulated storage.

Deploying Function Error on Cloud Function with error code 13 and Message "INTERNAL"

I'm deploying a Firestore trigger onCreate for my App, but everytime I want to deploy, it always Error
the console always showing Code 13 and Message "INTERNAL"
this is what comes up on Console
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{"code":13,"message":"INTERNAL"},
"authenticationInfo":{"principalEmail":"[My_EMAIL]"},
"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/etalase/locations/us-central1/functions/onNewMessage"}
this is my code on index.js
exports.onNewMessage = functions.firestore
.document('/messages/{groupChatId}/{groupChatId}/{messageFeedItem}')
.onCreate(async (snapshot, context) => {
const doc = snapshot.data();
console.log('------Message Created-----');
console.log(doc);
const idForm = doc.userID;
const idTo = doc.sellerID;
console.log('Message from : ', idForm);
console.log('Message to : ', idTo);
});
I expect this will deploy and every time a new message created on {messageFeedItem}, it will trigger the console, but even I can't deploy it
Thank you
So right now I can deploy the function by changing the directory
'messages/{groupChatId}/{groupChatId}/{messageFeedItem}'
into
'messages/{groupChatId}/{groupChatId2}/{messageFeedItem}'
my speculation is you can't have same name to the wildcard
You have to import firebase functions
import functions = require('firebase-functions');
or
const functions = require('firebase-functions');
If you did, then check your package.json
For anyone who got this far and still does not have a solution - here is what was wrong in my case
exports.fnName = functions.firestore
.document('Collection/{collId}/SubCollection/{subCollId')
.onUpdate((change, context) => {
...
});
Note the missing '} at the end of the document reference.
This caused the deploy to fail with the following on the client
Failed to configure trigger provider
And with the following in the function logs
"status":{
"code":13,
"message":"INTERNAL"
},
Set up Node.js and the Firebase CLI
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
my issue is because I use - character in my wild card
'chat/{abc-efg}'
I change - to _ and it works

Error parsing triggers Cannot find module when deploying firebase function

I am implementing a firebase function endpoint that requires I authenticate with two different projects. Information found on SO and other sources suggest this
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const serviceAccountSource = require('./source.json');
const serviceAccountTarget = require('./target.json');
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountSource)
})
const targetAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountTarget)
s}, "destination")
Where source.json and target.json are files storing the serviceAccount credentials (JSON) obtained from the Project Settings => Generate New Private Key.
My folder structure is as follows
functions/
index.ts
source.json
target.json
Running the following
npm run-script lint
produces no errors, however when I run
firebase deploy --only functions
I get
Error: Error parsing triggers: Cannot find module './source.json'
Firebase admin / functions versions as follows
"firebase-admin": "7.0.0",
"firebase-functions": "^2.2.0"
Typescript
"typescript": "^3.2.2"
Any ideas as what is causing the error.
If you are using Typescript try moving your source.json to the lib folder.
I found a solution to this. Although documentation on the firebase admin functions (parameters etc) seems to be very scarce I did notice that the credential.cert member takes a ServiceAccountPathOrObject.
I tried
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./source.json')
})
This failed with a path not found but this time it gave the path. From this I was able to see that there was a missing element in the Path
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./src/source.json')
})
The function deployed. I then tried to go back to the original code and added the 'src' folder to the path - however that resulted in the same error.
I prefer the above solution but I am still interested to know what caused the original error - given that much of the documentation out there seems to recommend this including this https://gist.github.com/brunobraga95/82bef0672ce451767107e62df1d8b28f - which is the code I am trying to implement.
The function has deployed and is working - so I can confirm the recommendation above works.

Error with Firebase on Electron app: Failed to load gRPC

I'm building an Electron app, and in the renderer.js file, I'm using Firebase Admin to get Firestore data. However, whenever I run it, it returns this error in the logs..
Error: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: electron-v2.0-darwin-x64-unknown
Found: [node-v48-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
I tried to run "npm rebuild", but it still didn't fix it.
I also tried updating Firebase Admin and gRPC.
Here is the code from the renderer.js file...
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const admin = require('firebase-admin');
var serviceAccount = require('./credentials.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mytestapp.firebaseio.com"
});
var db = admin.firestore();
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
function LoadList() {
db.collection("Orders").get().then(function(Collection){
Collection.forEach(function(OrderDoc){
console.log(OrderDoc.id)
})
}).catch(function(err){
console.error(err);
});
}
document.querySelector('#ListSec').addEventListener('click', LoadOrderList)
Any ideas? I've been trying to solve this for hours, but can't seem to figure it out.
That error message indicates that gRPC was installed for Node, not for Electron. Electron has a different binary interface, so binary modules like gRPC need to be installed specifically for Electron. You can generally do this just by running npm rebuild --runtime=electron --target=2.0.0 (modified to match the version of Electron you want to use).
The original answer by #murgatroid99 was helpful at the time, and a postinstall command worked great up until electron v7, where the issue returned.
For anyone else who comes across this issue, I've found a better solution:
the electron-rebuild package
npm install electron-rebuild --save-dev
Run it using
npx electron-rebuild
Or, add it as a postinstall command
{
...
"scripts": {
"postinstall": "electron-rebuild"
},
...
}
Further information is in the official Electron Documentation

Resources