-
-
Notifications
You must be signed in to change notification settings - Fork 495
feat(analytics): add getAppInstanceId for use with ga4 measurement protocol #962
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
…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]>
WalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.javaThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this 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
setUserIdandsetUserPropertyOptional 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
📒 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, returnsCDVCommandStatus_OKwith the ID orCDVCommandStatus_ERRORwith 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]>
There was a problem hiding this 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 clarityThe callback type
string | nullis 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 ): voidIf 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
📒 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 goodAnchor matches the new section and placement under Analytics is correct.
| ### 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); | ||
| }); | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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:
- Consent gating behavior - whether getAppInstanceId actually returns null under consent denial, as the reviewer suggests
- 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
PR Type
What kind of change does this PR introduce?
PR Checklist
Please check your PR fulfills the following requirements:
Bugfixes:
New features/enhancements:
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 theapp_instance_idparameter.The implementation includes:
FirebaseAnalytics.getAppInstanceId()[FIRAnalytics appInstanceID]Does this PR introduce a breaking change?
What testing has been done on the changes in the PR?
What testing has been done on existing functionality?
setUserId,setUserProperty,logEvent, etc.) continue to work correctlyOther 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:
app_instance_idparameter in Measurement Protocol requestsSummary by CodeRabbit
New Features
Documentation