Skip to content

[🐛] Bug Report - bucket not being found on Android #8002

Open

Description

@bastiaanno

🔥 Issue: Firebase Storage - [storage/unknown] Please use a gs:// URL for your Firebase Storage bucket on Android

Issue

I'm encountering an issue with Firebase Storage on Android where the error [storage/unknown] Please use a gs:// URL for your Firebase Storage bucket is thrown. This issue only occurs on Android; the iOS version works correctly.
Realtime database, app-check and analytics all work correctly as well.

I've verified that the google-services.json file is correctly configured, and the storage bucket is correctly recognized by Firebase, as evidenced by logging storageRef.bucket, which returns app.appspot.com. However, despite the correct configuration, Firebase Storage fails to retrieve files on Android, throwing the aforementioned error.


Project Files

Javascript

package.json:

`{
  "project_info": {
    "project_number": "__redacted",
    "firebase_url": "__redacted__",
    "project_id": "__redacted__",
    "storage_bucket": "__redacted__"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:__redacted__",
        "android_client_info": {
          "package_name": "__redacted__"
        }
      },
      "oauth_client": [],
      "api_key": [
        {
          "current_key": "__redacted__"
        }
      ],
      "services": {
        "appinvite_service": {
          "other_platform_oauth_client": []
        }
      }
    }
  ],
  "configuration_version": "1"
}`

firebase.json for react-native-firebase v6:

# Not set.

Android

Have you converted to AndroidX?

  • 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 {
    ext {
        buildToolsVersion = findProperty('android.buildToolsVersion') ?: '34.0.0'
        minSdkVersion = Integer.parseInt(findProperty('android.minSdkVersion') ?: '23')
        compileSdkVersion = Integer.parseInt(findProperty('android.compileSdkVersion') ?: '34')
        targetSdkVersion = Integer.parseInt(findProperty('android.targetSdkVersion') ?: '34')
        kotlinVersion = findProperty('android.kotlinVersion') ?: '1.9.23'

        ndkVersion = "26.1.10909125"
    }
    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')
    }
}

apply plugin: "com.facebook.react.rootproject"

allprojects {
    repositories {
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url(new File(['node', '--print', "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), '../android'))
        }
        maven {
            // Android JSC is installed from npm
            url(new File(['node', '--print', "require.resolve('jsc-android/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim(), '../dist'))
        }

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

android/app/build.gradle:

apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"

def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()

static def versionToNumber(major, minor, patch) {
  return patch * 100 + minor * 10000 + major * 1000000
}

def getRNVersion() {
  def version = providers.exec {
    workingDir(projectDir)
    commandLine("node", "-e", "console.log(require('react-native/package.json').version);")
  }.standardOutput.asText.get().trim()

  def coreVersion = version.split("-")[0]
  def (major, minor, patch) = coreVersion.tokenize('.').collect { it.toInteger() }

  return versionToNumber(
      major,
      minor,
      patch
  )
}
def rnVersion = getRNVersion()

/**
 * This is the configuration block to customize your React Native Android app.
 * By default you don't need to apply any configuration, just uncomment the lines you need.
 */
react {
    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()

    // 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"

    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
    // codegenDir = file("../node_modules/@react-native/codegen")

    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]

    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]

    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []

    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]

    if (rnVersion >= versionToNumber(0, 75, 0)) {
        /* Autolinking */
        autolinkLibrariesWithApp()
    }
}

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()

/**
 * The preferred build flavor of JavaScriptCore (JSC)
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

android {
    ndkVersion rootProject.ext.ndkVersion

    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdk rootProject.ext.compileSdkVersion

    namespace '__redacted__'
    defaultConfig {
        applicationId '__redacted__'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0.0"
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false)
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            crunchPngs (findProperty('android.enablePngCrunchInReleaseBuilds')?.toBoolean() ?: true)
        }
    }
    packagingOptions {
        jniLibs {
            useLegacyPackaging (findProperty('expo.useLegacyPackaging')?.toBoolean() ?: false)
        }
    }
}

// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
    // Split option: 'foo,bar' -> ['foo', 'bar']
    def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
    // Trim all elements in place.
    for (i in 0..<options.size()) options[i] = options[i].trim();
    // `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
    options -= ""

    if (options.length > 0) {
        println "android.packagingOptions.$prop += $options ($options.length)"
        // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
        options.each {
            android.packagingOptions[prop] += it
        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";

    if (isGifEnabled) {
        // For animated gif support
        implementation("com.facebook.fresco:animated-gif:${reactAndroidLibs.versions.fresco.get()}")
    }

    if (isWebpEnabled) {
        // For webp support
        implementation("com.facebook.fresco:webpsupport:${reactAndroidLibs.versions.fresco.get()}")
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation("com.facebook.fresco:animated-webp:${reactAndroidLibs.versions.fresco.get()}")
        }
    }

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

if (rnVersion < versionToNumber(0, 75, 0)) {
    apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
    applyNativeModulesAppBuildGradle(project)
}

apply plugin: 'com.google.gms.google-services'

android/settings.gradle:

  def version = providers.exec {
    commandLine("node", "-e", "console.log(require('react-native/package.json').version);")
  }.standardOutput.asText.get().trim()
  def (_, reactNativeMinor, reactNativePatch) = version.split("-")[0].tokenize('.').collect { it.toInteger() }

  includeBuild(new File(["node", "--print", "require.resolve('@react-native/gradle-plugin/package.json')"].execute(null, rootDir).text.trim()).getParentFile().toString())
  if(reactNativeMinor == 74 && reactNativePatch <= 3){
    includeBuild("react-settings-plugin")
  }
}

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

def getRNMinorVersion() {
  def version = providers.exec {
    commandLine("node", "-e", "console.log(require('react-native/package.json').version);")
  }.standardOutput.asText.get().trim()

  def coreVersion = version.split("-")[0]
  def (major, minor, patch) = coreVersion.tokenize('.').collect { it.toInteger() }

  return minor
}

if (getRNMinorVersion() >= 75) {
  extensions.configure(com.facebook.react.ReactSettingsExtension) { ex ->
    if (System.getenv('EXPO_UNSTABLE_CORE_AUTOLINKING') == '1') {
      println('\u001B[32mUsing expo-modules-autolinking as core autolinking source\u001B[0m')
      def command = [
        'node',
        '--no-warnings',
        '--eval',
        'require(require.resolve(\'expo-modules-autolinking\', { paths: [require.resolve(\'expo/package.json\')] }))(process.argv.slice(1))',
        'react-native-config',
        '--json',
        '--platform',
        'android'
      ].toList()
      ex.autolinkLibrariesFromCommand(command)
    } else {
      ex.autolinkLibrariesFromCommand()
    }
  }
}

rootProject.name = 'Project'

dependencyResolutionManagement {
  versionCatalogs {
    reactAndroidLibs {
      from(files(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../gradle/libs.versions.toml")))
    }
  }
}

apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle");
useExpoModules()

if (getRNMinorVersion() < 75) {
  apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
  applyNativeModulesSettingsGradle(settings)
}

include ':app'
includeBuild(new File(["node", "--print", "require.resolve('@react-native/gradle-plugin/package.json', { paths: [require.resolve('react-native/package.json')] })"].execute(null, rootDir).text.trim()).getParentFile())

AndroidManifest.xml:

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  <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">
    <meta-data android:name="com.google.android.geo.API_KEY" android:value="___redacted___"/>
    <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="__redacted__"/>
        <data android:scheme="exp+app"/>
      </intent-filter>
    </activity>
    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>
    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
  </application>
</manifest>

Environment

react-native info output:

 System:
  OS: macOS 14.6.1
  CPU: (8) arm64 Apple M1 Pro
  Memory: 134.27 MB / 16.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 20.17.0
    path: /opt/homebrew/opt/node@20/bin/node
  Yarn:
    version: 1.22.22
    path: /usr/local/bin/yarn
  npm:
    version: 10.8.2
    path: /opt/homebrew/opt/node@20/bin/npm
  Watchman:
    version: 2024.08.26.00
    path: /opt/homebrew/bin/watchman
Managers:
  CocoaPods:
    version: 1.15.2
    path: /opt/homebrew/bin/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 23.5
      - iOS 17.5
      - macOS 14.5
      - tvOS 17.5
      - visionOS 1.2
      - watchOS 10.5
  Android SDK: Not Found
IDEs:
  Android Studio: 2024.1 AI-241.15989.150.2411.11948838
  Xcode:
    version: 15.4/15F31d
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.12
    path: /usr/bin/javac
  Ruby:
    version: 2.6.10
    path: /usr/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.74.5
    wanted: ^0.74.5
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: false

info React Native v0.75.2 is now available (your project is running on v0.74.5).
info Changelog: https://github.com/facebook/react-native/releases/tag/v0.75.2
info Diff: https://react-native-community.github.io/upgrade-helper/?from=0.74.5
info For more info, check out "https://reactnative.dev/docs/upgrading?os=macos".
  • Platform that you're experiencing the issue on:
    • iOS
    • Android
    • iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • react-native-firebase version you're using that has this issue:
    • e.g. 5.4.3
  • Firebase module(s) you're using that has the issue:
    • Storage
  • Are you using TypeScript?
    • N

Activity

  1. changed the title [-][🐛] Bug Report Title - bucket not being found[/-] [+][🐛] Bug Report - bucket not being found on Android[/+] on Sep 1, 2024
  2. russellwheatley commented on Sep 2, 2024

    @russellwheatley
    Member

    Hey @bastiaanno - please provide a code sample of what you're doing and I can take a look. Thanks.

  3. bastiaanno commented on Sep 2, 2024

    @bastiaanno
    Author

    Hi,

    I'm trying the following:

    import firebase from "@react-native-firebase/app";
    import "@react-native-firebase/app-check";
    import "@react-native-firebase/database";
    import "@react-native-firebase/storage";
    import "@react-native-firebase/analytics";
    
    var rnfbProvider = firebase.appCheck().newReactNativeFirebaseAppCheckProvider();
    rnfbProvider.configure({
      android: {
        provider: __DEV__ ? "debug" : "playIntegrity",
        debugToken: "___redacted___",
      },
      apple: {
        provider: __DEV__ ? "debug" : "appAttestWithDeviceCheckFallback",
        debugToken: "___redacted___",
      },
    });
    firebase.database().setPersistenceEnabled(true);
    firebase.appCheck().initializeAppCheck({
      provider: rnfbProvider,
      isTokenAutoRefreshEnabled: true,
    });
    export default firebase;
    

    Images are loaded into a react use state on several pages using the following function:

    import firebase from "./firebase/firebase";
    const getImages = ({ variable, setterFunction }) => {
      firebase
        .storage()
        .ref()
        .list()
        .then((result) => {
          // Loop over each item
          result.items.forEach((item) => {
            item.getDownloadURL().then((value) => {
              variable.push({ imageUrl: value, imageName: item.name });
              setterFunction([...variable]);
            });
          });
        });
    };
    export default getImages;
    

    On iOS, images are being retrieved and displayed when used. On Android, the following error is returned:

    [storage/unknown] Please use a gs:// URL for your Firebase Storage
    

    Please reply if you need anything more.

  4. russellwheatley commented on Sep 3, 2024

    @russellwheatley
    Member

    Hi @bastiaanno - yes, could you please locate the exact API that is throwing the exception, and provide a small reproducible sample for me to test. Thanks 🙏

  5. bastiaanno commented on Sep 5, 2024

    @bastiaanno
    Author

    Hi, @russellwheatley, do you mean my firebase api?

  6. 16 remaining items

  7. bastiaanno commented on Nov 8, 2024

    @bastiaanno
    Author

    I have tested the following:

    import storage from "@react-native-firebase/storage";
    
    // Initialize storage with a custom bucket
    const customStorage = storage().app.storage("gs://testbucket-a0");
    
    const getUrl = () => {
      customStorage
        .ref("/IMG_2647.jpeg")
        .getDownloadURL()
        .then((url) => {
          console.log("File URL:", url);
        })
        .catch((error) => {
          console.error("Error fetching file:", error);
        });
    };
    export default getUrl;

    This returns:
    File URL: https://firebasestorage.googleapis.com/v0/b/testbucket-a0/o/IMG_2647.jpeg?alt=media&token=f5b956cc-7950-409e-ad46-8c9b1e575a21
    as it should.
    However,

    import storage from "@react-native-firebase/storage";
    
    // Initialize storage with a custom bucket
    const customStorage = storage().app.storage("gs://testbucket-a0");
    
    const loadUrl = () => {
      customStorage
        .ref("/")
        .list()
        .then((l) => {
          console.log(l);
        });
    };
    export default loadUrl;

    returns: Error listing items: [Error: [storage/unknown] Please use a gs:// URL for your Firebase Storage bucket.]

    If I move the file IMG_2647.jpeg to a folder named folder and use the following code:

    import storage from "@react-native-firebase/storage";
    
    // Initialize storage with a custom bucket
    const customStorage = storage().app.storage("gs://testbucket-a0");
    
    const loadUrl = () => {
      customStorage
        .ref("folder")
        .list()
        .then((l) => {
          console.log(l.items);
        });
    };
    export default loadUrl;

    the following is miraculously retuned:
    [{"_storage": {"_app": [FirebaseApp], "_config": [Object], "_customUrlOrRegion": "gs://testbucket-a0", "_maxDownloadRetryTime": 600000, "_maxOperationRetryTime": 120000, "_maxUploadRetryTime": 600000, "_nativeModule": [Object], "emulatorHost": undefined, "emulatorPort": 0}, "path": "folder/IMG_2647.jpeg"}]

    which means the issue is not there anymore.

    However, please note: this issue is not present on iOS! so this is most definitely a bug specific to Android.

    This is either an issue in the react-native-firebase/storage library where empty ref() calls do not result in the right bucket URL, or an issue in the documentation:

    (method) FirebaseStorageTypes.Module.ref(path?: string): FirebaseStorageTypes.Reference
    Returns a new storage.Reference instance.

    Example
    const ref = firebase.storage().ref('cats.gif');
    @param path
    An optional string pointing to a location on the storage bucket. If no path is provided, the returned reference will be the bucket root path.
    

    The path is not optional, and therefore when not supplied, the returned reference will not be the root path.
    ref(), ref(""), ref("/") do not but should work in my opinion.

    I hope this is more information that helps to narrow down the cause of the issue.

  8. github-actions commented on Dec 6, 2024

    @github-actions
  9. github-actions commented on Jan 8, 2025

    @github-actions
  10. mikehardy commented on Jan 23, 2025

    @mikehardy
    Collaborator

    This looks like it has the information required and is a platform difference

  11. added
    Keep Openavoids the stale bot
    and removed on Jan 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions