Skip to content

Conversation

@arsa-dev
Copy link

@arsa-dev arsa-dev commented Nov 17, 2025

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Documentation changes
  • Other... Please describe:

PR Checklist

Please check your PR fulfills the following requirements:

Bugfixes:

  • Regression testing has been carried out using the example project to ensure the intended bug is fixed and no regression bugs have been inadvertently introduced.

New features/enhancements:

  • Exhaustive testing has been carried out for the new functionality
  • Regression testing has been carried out to ensure no existing functionality is adversely affected
  • Documentation has been added / updated
  • The example project has been update to validate/demonstrate the new functionality.

What is the purpose of this PR?

This PR adds a new getAppInstanceId() method to retrieve the Firebase Analytics app instance ID. This ID is required for use with the Google Analytics Measurement Protocol to join Measurement Protocol events with online interactions using the app_instance_id parameter.

The implementation includes:

  • Android implementation using FirebaseAnalytics.getAppInstanceId()
  • iOS implementation using [FIRAnalytics appInstanceID]
  • JavaScript API wrapper
  • TypeScript definitions
  • Documentation with usage examples

Does this PR introduce a breaking change?

  • Yes
  • No

What testing has been done on the changes in the PR?

  • Manual testing on Android and iOS platforms to verify the method returns a valid app instance ID
  • Verified error handling for edge cases (null/empty values)
  • Confirmed the method works correctly with Firebase Analytics initialized

What testing has been done on existing functionality?

  • Verified that existing Analytics methods (setUserId, setUserProperty, logEvent, etc.) continue to work correctly
  • Confirmed no regressions in plugin initialization or other Firebase functionality

Other information

This feature enables integration with the Google Analytics Measurement Protocol, which allows sending events directly to Google Analytics servers via HTTP requests. The app instance ID is essential for properly joining server-to-server events with client-side analytics data.

Related documentation:

Summary by CodeRabbit

  • New Features

    • Added getAppInstanceId API to retrieve the Firebase Analytics app instance ID with success/error callback support across platforms.
  • Documentation

    • Updated public API docs and table of contents with usage examples and parameter descriptions for getAppInstanceId.

…otocol

- Implemented getAppInstanceId for both Android and iOS platforms to retrieve the app instance ID.
- Updated README.md to include documentation for the new method.
- Added TypeScript definitions for getAppInstanceId in index.d.ts.
- Enhanced firebase.js to expose the new method for use in JavaScript.

Signed-off-by: Antonio Ramón Sánchez Morales <[email protected]>
@coderabbitai
Copy link

coderabbitai bot commented Nov 17, 2025

Walkthrough

Adds a new public API getAppInstanceId that returns the Firebase Analytics app instance identifier; implemented in JavaScript bridge, Android and iOS native code, TypeScript definitions, and documented in README.

Changes

Cohort / File(s) Summary
Documentation
README.md
Added getAppInstanceId entry under Analytics, usage example, and TOC link.
JavaScript bridge
www/firebase.js
Added exports.getAppInstanceId = function(success, error) that calls native "getAppInstanceId" via cordova.exec.
Android implementation
src/android/FirebasePlugin.java
Added "getAppInstanceId" action mapping in execute and new private getAppInstanceId(final CallbackContext) which calls mFirebaseAnalytics.getAppInstanceId() with an OnCompleteListener, handles success/error and exceptions.
iOS implementation
src/ios/FirebasePlugin.h, src/ios/FirebasePlugin.m
Declared and implemented - (void)getAppInstanceId:(CDVInvokedUrlCommand*)command; runs in background, retrieves FIRAnalytics appInstanceID, sends success or error plugin result, with exception handling.
Type definitions
types/index.d.ts
Added optional `getAppInstanceId(success?: (appInstanceId: string

Sequence Diagram(s)

sequenceDiagram
    participant JS as JavaScript (www/firebase.js)
    participant Native as Plugin (Android/iOS)
    participant SDK as Firebase Analytics SDK

    JS->>Native: exec("getAppInstanceId")
    activate Native
    Native->>SDK: request appInstanceId (async)
    activate SDK
    SDK-->>Native: appInstanceId (success) / error
    deactivate SDK
    Native-->>JS: pluginResult OK with appInstanceId / ERROR with message
    deactivate Native
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review areas to focus on:
    • Android: correct use of getAppInstanceId() async listener and thread handling.
    • iOS: background thread usage and null/empty handling of appInstanceID.
    • JS/TS: API shape consistency with other bridge methods and typings.
    • README: accuracy of example and TOC link.

Poem

🐰 I hopped from docs to native land,

JS call, a tiny helping hand,
Analytics whisper their ID so bright,
Returned to me in morning light,
A little hop — all systems right. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding a getAppInstanceId method for Firebase Analytics GA4 Measurement Protocol integration.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.39.9)
src/android/FirebasePlugin.java

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
README.md (1)

2584-2601: Document null/consent and GA4 prerequisites.

  • Note that the returned value can be null if Analytics storage consent is denied or Analytics collection is disabled. (firebase.google.com)
  • Add a sentence that GA4 Measurement Protocol events require an app_instance_id previously observed by the Firebase SDK for that app; otherwise events won’t attribute. (developers.google.com)
src/ios/FirebasePlugin.m (1)

1753-1778: LGTM! Solid implementation following established patterns.

The implementation correctly:

  • Runs on a background thread (consistent with other analytics methods)
  • Uses the appropriate Firebase API [FIRAnalytics appInstanceID]
  • Handles nil and empty values defensively
  • Follows the plugin's exception handling conventions
  • Maintains consistency with similar methods like setUserId and setUserProperty

Optional enhancement: The error message could be more helpful for debugging by mentioning potential causes:

-            } else {
-                NSString *errorMessage = @"Failed to get app instance ID: value is nil or empty";
+            } else {
+                NSString *errorMessage = @"Failed to get app instance ID: value is nil or empty. Ensure Firebase Analytics is initialized and collection is enabled.";
                 pluginResult = [CDVPluginResult
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63eb1ba and f36ca56.

📒 Files selected for processing (6)
  • README.md (2 hunks)
  • src/android/FirebasePlugin.java (2 hunks)
  • src/ios/FirebasePlugin.h (1 hunks)
  • src/ios/FirebasePlugin.m (1 hunks)
  • types/index.d.ts (1 hunks)
  • www/firebase.js (1 hunks)
🔇 Additional comments (4)
README.md (1)

120-121: TOC entry for getAppInstanceId: OK.

www/firebase.js (1)

203-206: LGTM.

Bridges action correctly; will surface null as-is to the success callback, which aligns with native behavior.

If you want parity with other APIs, consider adding a short note in README that success may receive null depending on consent.

src/ios/FirebasePlugin.h (1)

80-80: API addition is properly wired and implements correct null/consent handling.

  • iOS (line 1753–1780): Calls [FIRAnalytics appInstanceID], validates non-nil and non-empty, returns CDVCommandStatus_OK with the ID or CDVCommandStatus_ERROR with message.
  • Android (line 1169–1195): Calls mFirebaseAnalytics.getAppInstanceId() asynchronously, validates success and non-null result with length check, returns success or error callbacks accordingly.
  • Routing (Android line 364–366): "getAppInstanceId" case properly dispatched in execute() switch.
  • Consent: Firebase SDK methods inherit Analytics storage consent enforcement—no explicit checks needed.
src/android/FirebasePlugin.java (1)

364-366: LGTM! Action routing follows established patterns.

The routing logic correctly directs the "getAppInstanceId" action to the implementation method, consistent with other analytics actions in this switch statement.

- Updated error messages in iOS and Java to provide clearer guidance on potential issues with retrieving the app instance ID.
- Modified TypeScript definitions to allow for null values in the success callback.
- Revised README.md to reflect changes in app instance ID retrieval and consent behavior.
- Tested again android functionality

Signed-off-by: Antonio Ramón Sánchez Morales <[email protected]>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
types/index.d.ts (1)

151-154: Nullability handled correctly; add short JSDoc for clarity

The callback type string | null is correct given consent/collection states. Consider a brief JSDoc to prevent misuse and to distinguish from FID.

+    /**
+     * Returns the Firebase Analytics app instance ID used by GA4 Measurement Protocol (`app_instance_id`).
+     * May be `null` if Analytics storage consent is denied or Analytics collection is disabled.
+     * Not the same as Firebase Installation ID (see getInstallationId).
+     */
     getAppInstanceId(
         success?: (appInstanceId: string | null) => void,
         error?: (err: string) => void
     ): void

If your supported Firebase SDK versions document additional conditions where the ID can be null (e.g., after resetAnalyticsData), consider noting them.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f36ca56 and 665bdc2.

📒 Files selected for processing (4)
  • README.md (2 hunks)
  • src/android/FirebasePlugin.java (2 hunks)
  • src/ios/FirebasePlugin.m (1 hunks)
  • types/index.d.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/ios/FirebasePlugin.m
  • src/android/FirebasePlugin.java
🔇 Additional comments (1)
README.md (1)

120-120: TOC entry looks good

Anchor matches the new section and placement under Analytics is correct.

Comment on lines +2584 to +2601
### getAppInstanceId

Get the app instance ID for use with the [Google Analytics Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/ga4). The app instance ID is used to join Measurement Protocol events with online interactions using the `app_instance_id` parameter, but Measurement Protocol events will only attribute if the `app_instance_id` has already been observed by the Firebase SDK in that app session.

**Parameters**:

- {function} success - callback function which will be invoked on success.
Will be passed a {string} containing the app instance ID (or `null` if Analytics storage consent is denied or Analytics collection is disabled, per [Firebase Analytics consent behavior](https://firebase.google.com/docs/analytics/consent)).
- {function} error - (optional) callback function which will be passed a {string} error message as an argument

```javascript
FirebasePlugin.getAppInstanceId(function(appInstanceId) {
console.log("App Instance ID: " + appInstanceId);
// Use appInstanceId with Google Analytics Measurement Protocol
}, function(error) {
console.error("Error getting app instance ID: " + error);
});
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

Clarify GA4 Measurement Protocol attribution and add cross‑refs

Two tweaks:

  • Replace “only attribute if ... observed by the Firebase SDK in that app session” with “only attribute if the app_instance_id has been previously observed by the Firebase SDK for this app.” The “same session” requirement is stricter than GA4 docs imply; please verify. Also add a note that this ID is distinct from Firebase Installation ID (FID) exposed by getInstallationId.
  • Add a brief consent gating note so consumers expect null and can branch accordingly.

Suggested doc edit:

-Get the app instance ID for use with the Google Analytics Measurement Protocol (...). The app instance ID is used to join Measurement Protocol events with online interactions using the `app_instance_id` parameter, but Measurement Protocol events will only attribute if the `app_instance_id` has already been observed by the Firebase SDK in that app session.
+Get the Firebase Analytics app instance ID for use with the Google Analytics Measurement Protocol (...). Use the `app_instance_id` parameter to join Measurement Protocol events with client‑side analytics. Attribution occurs only after the same `app_instance_id` has been observed by the Firebase SDK for this app. (Not the same as the Firebase Installation ID (FID) returned by [getInstallationId](#getinstallationid).)
+
+Note: This method may return `null` until analytics consent/collection is granted/enabled. You can gate usage with `isAnalyticsCollectionEnabled` or set consent via `setAnalyticsConsentMode`.

Please verify the attribution wording against GA4 MP docs:

Optionally update the example to demonstrate a null check before using the ID.


🌐 Web query:

GA4 Measurement Protocol app_instance_id attribution previously observed session requirement

💡 Result:

Short answer

  • GA4 Measurement Protocol for App streams requires a valid app_instance_id that was already produced/used by the Firebase (Google Analytics for Firebase) SDK — Measurement Protocol events must include that app_instance_id to be accepted/verified. [1][2]
  • If you want those MP events to join/receive the same session attribution as an online session, include session_id and send the MP request within 24 hours of that session's start. For advertising export there are longer windows (e.g., up to 63 days for some use cases). [2][3]

Sources

  • Verify implementation (GA4 Measurement Protocol): app_instance_id must have been used by the Firebase SDK. [1]
  • Measurement Protocol use cases / session attribution and export windows (session_id within 24 hours; ad export up to 63 days). [2]
  • Measurement Protocol reference: session_id and engagement_time_msec requirements for session-based reporting. [3]

I need to verify two more aspects to complete the assessment:

  1. Consent gating behavior - whether getAppInstanceId actually returns null under consent denial, as the reviewer suggests
  2. FID distinction accuracy - whether the cross-reference to getInstallationId is correct

Based on my verification of the review comment against Firebase and GA4 documentation:

All review suggestions are accurate and well-founded

getAppInstanceId returns null if ANALYTICS_STORAGE consent is DENIED, confirming the consent gating note is appropriate. The app instance ID is associated with the Firebase Analytics instance, whereas the Installation ID covers broader scope and is used for various Firebase services, validating the distinction from getInstallationId. The GA4 MP wording change from "same session" to "previously observed by the Firebase SDK for this app" aligns with actual GA4 behavior, where session attribution requires session_id (not just app_instance_id in the same session).

Suggested documentation update is valid and recommended for:

  • Clarifying that app_instance_id is distinct from Firebase Installation ID
  • Adding consent gating behavior so developers expect null and can branch accordingly
  • Improving GA4 MP attribution explanation
  • Demonstrating null check pattern in example code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant