Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulated firstore: Firestore (8.5.0): Could not reach Cloud Firestore backend

Sorry for the title, I'm not sure if this is the correct problem I'm facing but, I'll try and describe what I'm trying to do.

I've updated the title as the error in it seems to be my issue (original: "Emulated firstore not saving documents?").

I have a React app that uses Firebase on prod (functions, auth, firestore & storage) and I need to change some stuff on there so, I thought it would be safer to do these changes locally first then deploy them. So, I set up the firebase emulator suite and set up the app's environment variables to point to the local stuff (storage isn't needed for this part of the app so, it's not enabled locally).

Anyways, I set up a local auth account so I can log into the account and add a document to the "user" collection (this is needed because the app looks up the logged in user's document in firestore) however, it seems that the firestore emulator get's rid of this document when I refresh the emulator UI?

You can see what I mean in this GIF: Firestore getting rid of the document

Additional information that may be needed:

❯ firebase emulators:start --import ./functions/firestore --export-on-exit      
i  emulators: Starting emulators: auth, functions, firestore
!  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, hosting, pubsub, storage
+  functions: Using node@12 from host.
i  firestore: Importing data from E:\Project\api\functions\firestore\firestore_export\firestore_export.overall_export_metadata
!  firestore: Did not find a Cloud Firestore rules file specified in a firebase.json config file.
!  firestore: The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.
i  firestore: Firestore Emulator logging to firestore-debug.log
i  auth: Importing config from E:\Project\api\functions\firestore\auth_export\config.json
i  auth: Importing accounts from E:\Project\api\functions\firestore\auth_export\accounts.json
!  ui: Emulator UI unable to start on port 4000, starting on 4001 instead.
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "E:\Project\api\functions" for Cloud Functions...
+  functions[us-central1-auth]: http function initialized (http://localhost:5001/my-project/us-central1/auth).
i  functions[us-central1-backup-scheduledFirestoreExport]: function ignored because the pubsub emulator does not exist or is not running.
+  functions[us-central1-makeAdmin]: http function initialized (http://localhost:5001/my-project/us-central1/makeAdmin).
+  functions[us-central1-users]: http function initialized (http://localhost:5001/my-project/us-central1/users).

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4001                │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ localhost:9099 │ http://localhost:4001/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ localhost:5001 │ http://localhost:4001/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ localhost:8080 │ http://localhost:4001/firestore │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

I feel like this is the issue that's stopping me as the app prodcues an error in console

[2021-06-22T09:58:16.805Z]  @firebase/firestore: Firestore (8.2.4): 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.

which, is caused by the line

await firestore().doc(`users/${loggedInUser.uid}`).get();

I'm guessing this is because a user document with that UID doesn't exist (because I can't seem to create it).

The app's environment and firebase initialization:

REACT_APP_FIREBASE_AUTH_DOMAIN=http://localhost:9099
REACT_APP_FIREBASE_DATABASE_URL=http://localhost:8080
REACT_APP_FIREBASE_PROJECT_ID=my-project
REACT_APP_FIREBASE_STORAGE_BUCKET=my-project.appspot.com
REACT_APP_FIREBASE_FUNCTIONS_ENDPOINT=http://localhost:5001/my-project/us-central1

----- 

if (process.env.NODE_ENV !== 'production') {
  console.log("USING LOCAL EMULATORS");
  firebase.auth().useEmulator(process.env.REACT_APP_FIREBASE_AUTH_DOMAIN);
  firebase.firestore().useEmulator('localhost', 8080);
  firebase.functions().useEmulator('localhost', 5001);

  firebase.firestore.setLogLevel('debug');
}

node -v: v12.0.0 (it's what prod is running)

firebase --version: 9.13.1

Any help would be appreciated.

Edit: Even adding the user via a function doesn't work:

    const userDoc = await admin
      .auth()
      .createUser({
        email: safeUser.email,
        password: safeUser.password,
        displayName: `${safeUser.firstName} ${safeUser.lastName}`,
      });
  
    delete safeUser.password;
  
    await admin.firestore().collection('users').doc(userDoc.uid).set(safeUser);
    res.status(200).send(JSON.stringify({ uid: userDoc.uid, ...safeUser }));

Which does return the user

{
  "data": {
    "uid": "owLduAuMku520XVVm5J6qq92DPZp",
    "email": "[email protected]",
    "firstName": "Test",
    "lastName": "Account",
    "dob": "1900-01-01T00:00:00.000Z",
    "phoneNumber": "+447999999999"
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-length": "224",
    "content-type": "text/html; charset=utf-8"
  },
  "config": {
    "url": "http://localhost:5001/my-project/us-central1/createUser",
    "method": "post",
    "data": "{\"consent\":true,\"phoneNumber\":\"+447999999999\",\"dob\":\"1900-01-01T00:00:00.000Z\",\"password\":\"password\",\"email\":\"[email protected]\",\"firstName\":\"Test\",\"lastName\":\"Account\"}",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json;charset=utf-8"
    },
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1
  },
  "request": {}
}

However, it still doesn't show in the emulator UI (it created the auth user) and the log is normal:

i  functions: Beginning execution of "us-central1-createUser"
!  Received service account token ---- Assuming that it owns project "my-project".
!  Received service account token ---- Assuming that it owns project "my-project".
i  functions: Finished "us-central1-createUser" in ~2s

Edit 2: Opened the console on the emulator UI and when loading up the user collection I see the same error I see on the app:

[2021-06-22T11:44:56.597Z]  @firebase/firestore: Firestore (8.5.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.

Edit 3: It seems that connecting to a url at port 8080 temporarily fixes this issue. Going to the channel URL in a separate tab then allows firebase to load the data from it... Would changing the port fix the issue?

Edit 4: Changing the port did not fix the issue. It seems to be the URL below causing the issue:

http://localhost:8081/google.firestore.v1.Firestore/Listen/channel?database=projects%2Fmy-project%2Fdatabases%2F(default)&VER=8&RID=rpc&SID=FgqppSIdbuIaPmABDJD6fA%3D%3D&CI=0&AID=0&TYPE=xmlhttp&zx=yzaslurbjssn&t=1

No response from URL

Edit 5: Updating to the latest firebase module did not help

like image 504
Jordan Dalton Avatar asked Oct 15 '22 20:10

Jordan Dalton


1 Answers

Okay, so after a lot more research and looking around it seems that adding firebase.firestore().settings({ experimentalAutoDetectLongPolling: true }); fixes the issue on the app. It doesn't fix the issue with the UI (I would like it to work so I'vew got a visual of what's happening) but, I think I can put up with that for the time being.

For others with the same issue, this is my full firebase config:

if (process.env.NODE_ENV !== 'production') {
  console.log("USING LOCAL EMULATORS");
  firebase.auth().useEmulator(process.env.REACT_APP_FIREBASE_AUTH_DOMAIN);
  firebase.firestore().useEmulator('localhost', 8081);

  firebase.firestore().settings({ experimentalAutoDetectLongPolling: true }); //This seems to fix an issue with firestore emulator...

  var storage = firebase.storage();
  console.log("storage", storage);
  storage.useEmulator("localhost", 9199);

  firebase.functions().useEmulator('localhost', 5001);

  firebase.firestore.setLogLevel('debug');
}

If anyone know why this works or, how to get the emulator UI working please do tell. I'm still searching for answers!

Edit: If anyone else is having the same issue on Windows, try Linux! Seems to work perfectly fine there!

like image 113
Jordan Dalton Avatar answered Oct 25 '22 04:10

Jordan Dalton