javascriptfirebasegoogle-cloud-firestorefirebase-authenticationfirebase-app-check

Firestore Connection Issues and Unverified App Check Requests in Firebase Web App


Problem: I'm experiencing consistent issues with Firebase Firestore in my web application. Although authentication processes succeed (users are created in Firebase Auth), attempts to write to Firestore consistently fail with the following errors:

[Warning] Firestore (10.7.0): Connection - "WebChannel transport errored:" – ir {...}
[Error] Firestore (10.7.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: The operation could not be completed...
[Error] Error checking referral code uniqueness: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...
[Error] Error in signup process: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...

I'm not sure why the client would be offline.

Additionally, I'm encountering CORS-related errors, but this only happened while I was typing this up and I'm not sure what happened:

[Error] Cancelled load to https://www.gstatic.com/recaptcha/releases/.../styles__ltr.css because it violates the resource's Cross-Origin-Resource-Policy response header.

I'm not sure what triggered that either, because I don't have anything related to recaptcha in my code anywhere except for my site key and the script tags for app check.

Context and Troubleshooting Steps:

  1. This issue started occurring after attempting to implement Firebase App Check and reCAPTCHA, along with updating Firebase SDK from 9.6.10 to 10.7.0 and using modules instead of the global namespace. I reverted to using Firebase 9.6.10 and the global namespace instead of the modular approach, but the issue persists. I then updated back to 10.7.0 while using the global namespace and the issue still persists.

  2. App Check is set up in the Firebase console but not enforced. It showed all requests as unverified, then as verified, back to unverified, and then back to verified without any changes on my side.

  3. In reCAPTCHA, the requests are not marked as suspicious. But for some reason, requests are not being detected there anymore, it was jut requests from yesterday before I was really keeping track of what was going on.

  4. I thought CORS might be an issue, but there were no CORS issues before implementing App Check and reCAPTCHA.

  5. The issue occurs both on localhost and my deployed domain. Both are defined in Firebase and reCAPTCHA.

  6. Firebase Firestore rules have not been altered since the implementation was working correctly.

  7. Tested on different Wi-Fi networks and in incognito mode in a different browser.

  8. I also thought that maybe lite server wasn't able to handle it, so I moved to Vite and the errors are still happening in my dev environment.

  9. I have verified all my keys and stuff are correct

Firebase Configuration: Here's how I'm initializing Firebase in my web app:

const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "myauthdomain",
  projectId: "myprojectID",
  storageBucket: "mystoragebucket",
  messagingSenderId: "mysenderID",
  appId: "myappid",
  measurementId: "mymeasurementID"
};

firebase.initializeApp(firebaseConfig);
firebase.appCheck().activate('mysitekey', true);

HTML Script Tags:

<script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js" defer></script>
<!-- Additional Firebase service scripts -->
<script src="scripts/firebase.js" defer></script>
<!-- Additional custom scripts -->

Code Causing Errors: The following script triggers functions that throw errors related to Firestore:

function createUserAccount(email, password, referralCode = "") {
    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then((userCredential) => {
            console.log("User created with Firebase Auth, User ID:", userCredential.user.uid);
            const userId = userCredential.user.uid;

            return createUniqueReferralCode().then(newReferralCode => {
                console.log("Generated Unique Referral Code:", newReferralCode);

                // Create a user document in 'users' collection
                const userRef = firebase.firestore().doc('users/' + userId);
                userRef.set({
                    email: email,
                    referralsCount: 0
                });

                // Create a document in 'referralCodes' collection
                return firebase.firestore().collection('referralCodes').doc(newReferralCode).set({
                    ownerId: userId
                });
            });
        })
        .then(() => {
            // Call Cloud Function to update the referrer count
            if (referralCode) {
                return updateReferrerCountCloudFunction(referralCode);
            }
        })
        .then(() => {
            console.log("Redirecting to index.html");
            window.location.href = 'index.html'; // Redirect on successful signup
        })
        .catch((error) => {
            console.error("Error in signup process: ", error);
            document.getElementById('signup-error').innerText = error.message;
        });
}

Observations: Users are consistently created in Firebase Auth. Firestore document creation fails every time. Test signups authenticate users but fail to create documents in Firestore. Reverting back to the commit before this all started happening still has the issue.
There was a time when instead of failing immediately, it just timed out after 10 seconds. I don't know what I did to make that happen though, and it hasn't happened again.

Any insight is appreciated.


Solution

  • I figured it out. I had some async operations that hadn't finished yet before I was redirecting the page. So when I commented out the redirect to index.html lines everything worked as expected.