React Native Firebase problem with emulator on physical device - javascript

I am programming an app with React Native. To use Firebase in this app, I installed the React Native Firebase npm package. I have set up everything to make requests to Firebase functions and this works smoothly. I am currently trying to set up the Firebase functions emulator to make my dev journey easier. But I can't seem to connect to the emulator.
Client
import functions from '#react-native-firebase/functions';
const DEV = true
if (DEV) {
functions().useEmulator("192.168.x.x", 5001);
}
const sayHelloWorld = () =>{
functions()
.httpsCallable('helloWorld')()
.then(response => {
console.log(response.data)
});
}
sayHelloWorld()
Backend Function
exports.helloWorld = functions.https.onRequest((request, response) => {
response.status(200).send({"data":"Say hello world"});
});
I am using the useEmulator function to switch to the emulator running on port 5001. I am not using useFunctionEmulator as shown in the documentation (https://rnfirebase.io/functions/usage) because it appears to be outdated, but I tried it, and it doesn't work as well. I am using my local IP address for the host because I am running a physical android device. I have no issue running the app, but as soon as I execute the function request nothing happens and after one minute I get the following error message:
Possible Unhandled Promise Rejection (id: 0):
Error: DEADLINE_EXCEEDED
Error: DEADLINE_EXCEEDED
callFirebaseFunctions#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:116187:60
_performTransitionSideEffects#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65273:22
_receiveSignal#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65215:45
onResponderRelease#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65055:34
invokeGuardedCallbackProd#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:3940:21
invokeGuardedCallback#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4044:42
invokeGuardedCallbackAndCatchFirstError#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4048:36
executeDispatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4124:48
executeDispatchesInOrder#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4144:26
executeDispatchesAndRelease#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:5493:35
forEach#[native code]
The emulator logs do not show any activity.

Related

I Cannot Connect my Expo App to localhost Api

I am building a react native app using expo and I am trying to connect to a http://localhost/api running on my localhost. All I ma getting is network error.
The expo app is running on a real device. I did that using expo start --localhost --android
I have tried using the ip address provided by the ipconfig /all instead of localhost but I am still getting Network Error
Here is my code
const fetchApi = async () => {
try {
const res = await axios.get("http://10.2.0.56:8000/");
console.log(res.data);
} catch (error) {
console.log(error.message);
}
};
Somebody please help

Firebase App Check returned error status 500 in production (Web App)

I add Firebase App Check with reCAPTCHA Enterprise in my vue3 project(web app project), and work well on mode devel(debug provider). But when build on production, appcheck not working and return HTTP status: 500.
my appcheck config:
if (location.hostname === "127.0.0.1") {
self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
}
const appcheck = initializeAppCheck(app, {
provider: new ReCaptchaEnterpriseProvider(
import.meta.env.VITE_FIREBASE_RECAPTCHA_ENTERPRISE_KEY
),
isTokenAutoRefreshEnabled: true, // Set to true to allow auto-refresh.
});
error example :
https://content-firebaseappcheck.googleapis.com/v1/projects/app-name/apps/1:id:web:id:exchangeRecaptchaEnterpriseToken?key=xxxxxxxxxxxxxxxxxxxxxxxxxx 500
Firebase appcheck work after we generate new site key and replace the old one.
NB:
In our case, http error 500 occurs because one site key is used in android app and web app. We don't know if this is indeed the problem causing the error, but after separating site key (for android app and web app), firebase appcheck runs smoothly.

react native firebase authentication emulator error message thrown : Error: A network error

I am attempting to use the recently released firebase emulator suite. specifically the authentication emulator.
I have the emulator installed and have created an test user in the auth emulator. as follows:
Within my code I have:
if (firebase.apps.length === 0) {
console.log("setup.js: initializing firebase....")
firebase.initializeApp(firebaseConfig);
firebase.auth().useEmulator('http://localhost:9099/');
} else {
firebase.app(); // if already initialized, use that one
}
to utilized the emulator for authentication. alas I get the following network error:
Has anyone had success utilizing the firebase emulator suite with react native?

Firebase Cloud Messaging - getToken() error in JS SDK

I am developing an app for KaiOS, a fork of the old Firefox OS, for which apps are based on HTML5 + JS. When compiling and running on device, Firebase Cloud Messaging stops working. I receive an error as follows.
TypeError: 'applicationServerKey' member of
PushSubscriptionOptionsInit could not be converted to any of:
ArrayBufferView, ArrayBuffer.
I've followed the instructions in the Firebase docs here as well as this tutorial on setting up FCM for Progressive Web Apps here. I can confirm I am setting my key before calling getToken, as shown below:
import firebase from "firebase";
const messaging = firebase.messaging();
messaging.usePublicVapidKey("<my-key-from-firebase-settings>");
messaging.getToken().then((currentToken) => {
...
}).catch((err) => {
...
});
I have searched for the above error, but to no avail. Does anyone know what this error means or how to fix it? Running the application in the browser on my development machine, everything works perfectly.
Note: the app is written in Typescript
Firebase SDK Version: 7.12.0
It might not be of help to you but I recently experienced a similar error message in a different environment:
Error: Failed to execute 'subscribe' on 'PushManager': The provided
value is not of type '(ArrayBuffer or ArrayBufferView)'
It was fixed in version 7.13.2 of Firebase:
https://github.com/firebase/firebase-js-sdk/issues/2712
https://firebase.google.com/support/release-notes/js#version_7132_-_april_2_2020

How to use firestore emulator from client

I want to test locally my firebase functions.
These functions make firestore queries.
So i start the emulator firebase emulators:start and in my client i use firebase.functions().useFunctionsEmulator('http://localhost:5001').
My functions work well when i call them in my client. I can read/write data inside the firestore emulator.
The problem :
I want to read the firestore emulator data directly inside my client, like :
firebase.firestore().collection('tests').get().then(tests => {
console.log( tests.docs.map(test=>test.map) )
})
but i can't find how to set the firestore emulator inside my client.
here what i tried:
1) Firestore setting
firebase.firestore().settings({
host:'http://localhost:8080',
ssl:false
})
result :
i get #firebase/firestore: Firestore (6.3.5): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds. inside my client console.
The http request returns 'Not found'
2) Set the emulator url inside my firebaseConfig
var firebaseConfig = {
// ...
databaseURL: "http://localhost:8080",
// ...
}
firebase.initializeApp(firebaseConfig)
in this case, the remote server (https://firestore.googleapis.com..) is requested.
So i want to setup one of these two cases :
1) Using the remote firestore inside my functions emulators
OR
2) Using the local firestore emulator inside my client code.
Anyone has already done this ?
Install the testing lib
npm i -D #firebase/testing
Setup and start the emulator in another terminal:
firebase setup:emulators:firestore
firebase serve --only firestore
Setup the tests
const firebase = require("#firebase/testing");
// Helper function to setup test db
function authedApp(auth) {
return firebase
.initializeTestApp({ projectId: FIRESTORE_PROJECT_ID, auth })
.firestore();
}
// Setup methods
beforeEach(async () => {
// Clear the database between tests
await firebase.clearFirestoreData({ projectId: FIRESTORE_PROJECT_ID });
});
// Clean up apps between tests.
afterEach(async () => {
await Promise.all(firebase.apps().map(app => app.delete()));
});
Run the tests
it("should retrieve correct item", async () => {
// Init test db
const db = authedApp(null);
// Manually add item to collection
const ref = await db.collection(COLLECTION_NAME).add({name: 'test item'});
// Fetch item by id
const resp = await db.collection(COLLECTION_NAME).doc(ref.id).get();
// test the output
expect(resp).toBeDefined();
expect(resp).toEqual(expect.objectContaining({name: 'test item'}));
});
Of course your particular setup and circumstances will differ, but this at least should give you a general idea. More info: https://firebase.google.com/docs/rules/unit-tests
Note from 'Test your Cloud Firestore Security Rules'
Data written to the Cloud Firestore emulator is held in memory until
the emulator is stopped. If the emulator is run continuously, this may
have an impact on test isolation. To ensure that data written in one
test is not read in another, either explicitly clear your data with
clearFirestoreData, or assign a different project ID for each
independent test: when you call firebase.initializeAdminApp or
firebase.initializeTestApp, append a user ID, timestamp, or random
integer to the projectID.
Edit: I wrote a blog post a while back, which goes into more detail about the subject.
I had the same problem too. I found the following example, which looks like its still work in progress:
https://github.com/firebase/quickstart-nodejs/tree/master/firestore-emulator/browser-quickstart
They didn't use #firebase/testing directly in their example. When I did try to embed #firebase/testing in my webpack code, it tries to connect via grpc, which attempts to do fs.existsSync, which doesn't exist in webpack browser context. They prefer to enable the functionality via WebChannel instead.
Some caveats as of Nov 2019:
You might see errors in the console connecting to localhost:8080 with the X-Goog-API. I am not sure what is that for.
You might get the following error: #firebase/firestore: Firestore (6.3.5): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
Despite having those errors, my functions were still able to connect to the local firestore.
Versions I had at time I was testing:
firebase-js-sdk 6.3.1
firebase-tools 7.3.1
Update 11/18:
I raised an issue within quickstart-nodejs github and it seems I just needed to use the latest versions of everything.
Versions:
firebase-js-sdk v7.4.0
firebase-tools v7.8.0
Ok i found how to do it :
1) launch the functions emulator locally:
set GOOGLE_APPLICATION_CREDENTIALS=./privatekey.json && firebase serve --only functions
2) then client side:
if (process.env.NODE_ENV === 'development') {
firebase.functions().useFunctionsEmulator('http://localhost:5001')
}
Okay, this is trivial... In your firestore cient config you should have provided the host, not the origin for firestore (the protocol is set using the ssl parameter):
firebase.firestore().settings({
host: 'localhost:8080',
ssl: false
})
At least this solved it for me when I had the exact same error.
Just FYI to anyone who's reading this - if you run into problems with the firestore client, you can use debug level logging, just set firebase.firestore.setLogLevel('debug'). Had the OP done that, he might have noticed that firebase is accessing firestore at http://http://localhost:8080/...
Define the FIRESTORE_EMULATOR_HOST environment variable
If you are using a library that supports the FIRESTORE_EMULATOR_HOST environment variable, run:
export FIRESTORE_EMULATOR_HOST=localhost:8080
or just add FIRESTORE_EMULATOR_HOST=localhost:8080 to your .env file

Categories