react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

[🔥] Bug Report Title - FireStore can't connect to Cloud on Android emulator

Open wish-me-luck opened this issue 10 months ago • 2 comments

Issue

I've set up my db and collection and added a couple of sample documents. On Android emualtor, it just can't connect to the Fire Cloud DB. If I trigger the update() call, it will just hang forever. If I trigger the get() call, it instantly returns empty. Gemini suggested to listen to snapshot and print the connection type and it's all coming from "cache" .

I've definitely deleted the native folders and built the native app several times trying to clear out any prev issues. Also did a couple of Expo dev builds on cloud, not helping as well. Couldn't find any doc specific to Android Emualtor's connection issues.

This is my app.config.js

plugins: [ [ "expo-location", { locationAlwaysAndWhenInUsePermission: "Allow $(PRODUCT_NAME) to use your location.", isAndroidBackgroundLocationEnabled: true, }, ], "expo-router", "expo-web-browser", "expo-secure-store", ["expo-apple-authentication"], "@react-native-firebase/app", [ "expo-build-properties", { ios: { useFrameworks: "static", buildReactNativeFromSource: true, }, }, ], ], ios: { supportsTablet: true, config: { googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY, }, bundleIdentifier: "com.xxxxxxx", infoPlist: { ITSAppUsesNonExemptEncryption: false, }, googleServicesFile: "./GoogleService-Info.plist", }, android: { adaptiveIcon: { foregroundImage: "./assets/adaptive-icon.png", backgroundColor: "#ffffff", }, config: { googleMaps: { apiKey: process.env.GOOGLE_MAPS_API_KEY, }, }, googleServicesFile: "./google-services.json", permissions: [ "android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION", ], package: "com.xxxxxxx", },


Project Files

Javascript

Click To Expand

import firestore from "@react-native-firebase/firestore";

static async createThread( matchID: string, matchHost: string, createdBy: string, initialMessage?: string ): Promise { try { const db = firestore(); const app = db.app; const now = Date.now(); const unSeenMap: Map<string, boolean> = new Map(); unSeenMap.set(matchHost, false); unSeenMap.set(createdBy, true); const participants = [matchHost, createdBy]; const threadData: FirestoreThread = { matchID, creationTimestamp: now, threadStatus: "OPEN", participants, lastActivity: now, unseen: { [${createdBy}]: false, }, };

  // Gemini suggested adding these to debug, w/o this update() still hangs and get() retruns nothing as well.
  await firestore().terminate();
  console.log("about to clear persistence");

  await firestore().clearPersistence();
  console.log("Cache cleared");
  await firestore().settings({
    persistence: false,
    // Another suggestion from Gemini says might help
    ssl: true,
  });

  const collection = await db.collection("courts-mate-chats").get();

  db.collection("courts-mate-chats").onSnapshot((snapshot) => {

    // below always logs "Cache"
    console.log(
      "Source:",
      snapshot.metadata.fromCache ? "Cache" : "Server"
    );
    console.log("Documents found:", snapshot.size);
  });

  // Create thread document (let Firestore auto-generate ID) This part just hangs on Android.
  const threadRef = await db
    .collection("courts-mate-chats")
    .add(threadData);
  const threadID = threadRef.id;

  // If there's an initial message, send it
  if (initialMessage) {
    await FirestoreChatService.sendMessage(
      threadID,
      createdBy,
      participants,
      initialMessage
    );
  }

  console.log(`✅ Created thread ${threadID} for match ${matchID}`);
  return threadID;
} catch (error) {
  console.error(`❌ Failed to create thread for match ${matchID}:`, error);
  throw error;
}

}

package.json:

  "dependencies": {
    "@aws-amplify/react-native": "^1.2.0",
    "@aws-sdk/client-cognito-identity": "^3.577.0",
    "@aws-sdk/client-s3": "^3.940.0",
    "@babel/runtime": "^7.28.4",
    "@gluestack-style/react": "^1.0.57",
    "@gluestack-ui/config": "^1.1.20",
    "@gluestack-ui/themed": "^1.1.73",
    "@gorhom/bottom-sheet": "^5.2.6",
    "@react-native-async-storage/async-storage": "^2.1.2",
    "@react-native-community/netinfo": "^11.4.1",
    "@react-native-firebase/app": "23.8.3",
    "@react-native-firebase/firestore": "^23.8.3",
    "@react-native-picker/picker": "2.11.1",
    "aws-amplify": "6",
    "expo": "~54.0.31",
    "expo-apple-authentication": "~8.0.7",
    "expo-auth-session": "~7.0.8",
    "expo-build-properties": "~1.0.10",
    "expo-constants": "~18.0.10",
    "expo-crypto": "~15.0.7",
    "expo-dev-client": "~6.0.17",
    "expo-image-manipulator": "~14.0.7",
    "expo-image-picker": "~17.0.8",
    "expo-linking": "~8.0.8",
    "expo-location": "~19.0.7",
    "expo-router": "~6.0.14",
    "expo-secure-store": "~15.0.7",
    "expo-splash-screen": "~31.0.10",
    "expo-status-bar": "~3.0.8",
    "expo-system-ui": "~6.0.8",
    "expo-web-browser": "~15.0.9",
    "jose": "^6.0.11",
    "nativewind": "^4.2.1",
    "nullthrows": "^1.1.1",
    "react": "19.1.0",
    "react-dom": "19.1.0",
    "react-native": "0.81.5",
    "react-native-gesture-handler": "~2.28.0",
    "react-native-get-random-values": "^1.11.0",
    "react-native-gifted-chat": "^3.2.3",
    "react-native-keyboard-controller": "1.18.5",
    "react-native-maps": "1.20.1",
    "react-native-reanimated": "~4.1.1",
    "react-native-safe-area-context": "~5.6.0",
    "react-native-screens": "~4.16.0",
    "react-native-svg": "15.12.1",
    "react-native-vector-icons": "^10.3.0",
    "react-native-web": "^0.21.0",
    "react-native-worklets": "0.5.1",
    "toastify-react-native": "^7.2.3",
    "ts-node": "^10.9.1"
  },

firebase.json for react-native-firebase v6:

# N/A

iOS

Click To Expand

ios/Podfile:

  • [ x] I'm not using Pods
  • [] I'm using Pods and my Podfile looks like:
# N/A

AppDelegate.m:

// N/A


Android

Click To Expand

Have you converted to AndroidX?

  • [ x] my application is an AndroidX application?
  • [ ] I am using android/gradle.settings jetifier=true for Android compatibility?
  • [ ] I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

buildscript {
  repositories {
    google()
    mavenCentral()
  }
  dependencies {
        classpath 'com.google.gms:google-services:4.4.1'
    classpath('com.android.tools.build:gradle')
    classpath('com.facebook.react:react-native-gradle-plugin')
    classpath('org.jetbrains.kotlin:kotlin-gradle-plugin')
  }
}

allprojects {
  repositories {
    google()
    mavenCentral()
    maven { url 'https://www.jitpack.io' }
  }
}

apply plugin: "expo-root-project"
apply plugin: "com.facebook.react.rootproject"

android/app/build.gradle:

eact {
    entryFile = file(["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android", "absolute"].execute(null, rootDir).text.trim())
    reactNativeDir = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()
    hermesCommand = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc"
    codegenDir = new File(["node", "--print", "require.resolve('@react-native/codegen/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile().getAbsoluteFile()

    enableBundleCompression = (findProperty('android.enableBundleCompression') ?: false).toBoolean()
    // Use Expo CLI to bundle the app, this ensures the Metro config
    // works correctly with Expo projects.
    cliFile = new File(["node", "--print", "require.resolve('@expo/cli', { paths: [require.resolve('expo/package.json')] })"].execute(null, rootDir).text.trim())
    bundleCommand = "export:embed"

    autolinkLibrariesWithApp()
}

android/settings.gradle:

pluginManagement {
  def reactNativeGradlePlugin = new File(
    providers.exec {
      workingDir(rootDir)
      commandLine("node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })")
    }.standardOutput.asText.get().trim()
  ).getParentFile().absolutePath
  includeBuild(reactNativeGradlePlugin)
  
  def expoPluginsPath = new File(
    providers.exec {
      workingDir(rootDir)
      commandLine("node", "--print", "require.resolve('expo-modules-autolinking/package.json', { paths: [require.resolve('expo/package.json')] })")
    }.standardOutput.asText.get().trim(),
    "../android/expo-gradle-plugin"
  ).absolutePath
  includeBuild(expoPluginsPath)
}

plugins {
  id("com.facebook.react.settings")
  id("expo-autolinking-settings")
}

extensions.configure(com.facebook.react.ReactSettingsExtension) { ex ->
  if (System.getenv('EXPO_USE_COMMUNITY_AUTOLINKING') == '1') {
    ex.autolinkLibrariesFromCommand()
  } else {
    ex.autolinkLibrariesFromCommand(expoAutolinking.rnConfigCommand)
  }
}
expoAutolinking.useExpoModules()

rootProject.name = 'xxxxx'

expoAutolinking.useExpoVersionCatalog()

include ':app'
includeBuild(expoAutolinking.reactNativeGradlePlugin)

MainApplication.java:

class MainApplication : Application(), ReactApplication {

  override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper(
      this,
      object : DefaultReactNativeHost(this) {
        override fun getPackages(): List<ReactPackage> =
            PackageList(this).packages.apply {
              // Packages that cannot be autolinked yet can be added manually here, for example:
              // add(MyReactNativePackage())
            }

          override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry"

          override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

          override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
      }
  )

  override val reactHost: ReactHost
    get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost)

  override fun onCreate() {
    super.onCreate()
    DefaultNewArchitectureEntryPoint.releaseLevel = try {
      ReleaseLevel.valueOf(BuildConfig.REACT_NATIVE_RELEASE_LEVEL.uppercase())
    } catch (e: IllegalArgumentException) {
      ReleaseLevel.STABLE
    }
    loadReactNative(this)
    ApplicationLifecycleDispatcher.onApplicationCreate(this)
  }

  override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
  }
}

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <uses-permission android:name="android.permission.RECORD_AUDIO"/>
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.VIBRATE"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <queries>
    <intent>
      <action android:name="android.intent.action.VIEW"/>
      <category android:name="android.intent.category.BROWSABLE"/>
      <data android:scheme="https"/>
    </intent>
  </queries>
  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="true" android:theme="@style/AppTheme" android:supportsRtl="true" android:enableOnBackInvokedCallback="false" android:fullBackupContent="@xml/secure_store_backup_rules" android:dataExtractionRules="@xml/secure_store_data_extraction_rules">
    <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyAItjvLQlOWKT-RhNLW4PDFxK-tUopLqoo"/>
    <meta-data android:name="expo.modules.updates.ENABLED" android:value="false"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ALWAYS"/>
    <meta-data android:name="expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS" android:value="0"/>
    <activity android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:exported="true" android:screenOrientation="portrait">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="xxxxx"/>
        <data android:scheme="exp+xxxxx"/>
      </intent-filter>
    </activity>
    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
  </application>
</manifest>


Environment

Click To Expand

react-native info output:

 OUTPUT GOES HERE
  • Platform that you're experiencing the issue on:
    • [ ] iOS
    • [ ] Android
    • [ ] iOS but have not tested behavior on Android
    • [ x] Android but have not tested behavior on iOS
    • [ ] Both
  • react-native-firebase version you're using that has this issue:
    • 54.0.31
  • Firebase module(s) you're using that has the issue:
    • firebase.app('[DEFAULT]').firestore
  • Are you using TypeScript?
    • Y & 5.9.2


wish-me-luck avatar Jan 24 '26 07:01 wish-me-luck

This is not reproduced, there is no problem connecting to the firestore emulator in any version to date

If you can link to a repository that reproduces it, we could troubleshoot, but our e2e suite uses it all the time so the burden of proof is on reporter to provide running repo

mikehardy avatar Jan 24 '26 12:01 mikehardy

Thanks Mike, finally figured it out. The default constructor uses "{default}" as the database id. I unfortunately has given my first fireDB a specific name. Funny, couldn't find much docs on this... and feels so dumb lol

wish-me-luck avatar Jan 28 '26 07:01 wish-me-luck