Guides
Plan-enterprise-icon
Expo Application Services
API Reference

FirebaseAnalytics

Info-icon
This is the only Firebase Analytics package for React Native that has universal platform support (iOS, Android, Web, and Electron).
expo-firebase-analytics provides a unified native and web API for Google Analytics for Firebase, including partial Expo Go compatibility. Google Analytics for Firebase is a free app measurement solution that provides insight on app usage and user engagement. Learn more in the official Firebase Docs.

Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb
Status-success-iconStatus-success-iconStatus-success-iconStatus-success-iconStatus-success-icon

Installation

Terminal
→ npx expo install expo-firebase-analytics

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

When using the web platform, you'll also need to run the npx expo install firebase, to install the Firebase JS SDK.

Configuration

Additional configuration for iOS

expo-firebase-analytics uses native Firebase libraries on iOS that require additional configuration using the expo-build-properties config plugin. Install the plugin and apply the following configuration to your Expo config file.
Terminal
→ npx expo install expo-build-properties

Example app.json with config plugin

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-build-properties",
        {
          "ios": {
            "useFrameworks": "static"
          }
        }
      ]
    ]
  }
}

With React Native Firebase

If you are using expo-firebase-analytics with React Native Firebase, you'll have to install the native Firebase SDK using the npx expo install command:
Terminal
→ npx expo install @react-native-firebase/app
This will ensure that the @react-native-firebase/app dependency version is compatible with the Expo SDK version your project uses.
Also, make sure that you have React Native Firebase set up correctly in your project. For more information on how to set it up, see Install and initialize React Native Firebase.

Expo Go: Limitations & configuration

The use of native Firebase Analytics requires that the Google services configuration is bundled and linked into your app. Since Expo Go loads projects on demand, it does not have the Google services configuration linked into the app bundle.
Expo Go relies on a JavaScript-based implementation of Firebase Analytics to log events. This means that certain native life-cycle events are not recorded in the standard client, but you can still use logEvent() method to record events.
You can use Firebase Analytics in Expo Go to verify that you are logging events when you intend to, and with the data you want to attach without having to build an application binary that can be submitted to app stores. To set this up, ensure that the Firebase web configuration is set in app.json and that measurementId exists in your firebase config.
Here is an example of how to configure app.json to add measurementId:
app.json
{
  "expo": {
    "web": {
      "config": {
        "firebase": {
          "apiKey": "AIzaXXXXXXXX-xxxxxxxxxxxxxxxxxxx",
          ...
          "measurementId": "G-XXXXXXXXX"
        }
      }
    }
  }
}
If measurementId doesn't exist, then you need to enable or update Google Analytics in your Firebase project.
Info-icon
This limitation only applies to the Expo Go app in the App and Play stores; standalone builds, custom clients & bare apps support the full native Firebase Analytics experience.

Usage

Logging event

You can gain deeper insight into what works and what doesn't by using the logEvent property.
/*
 * Say we are in a tinder clone, and a user presses the card to view more
 * information on a user. We should track this event so we can see if people
 * are even using it.
 *
 * If lots of users are opening the card then swiping through photos, just
 * to dismiss again, then we should consider making it possible to look
 * through photos without having to enter the profile.
 */
onPressProfileButton = uid => {
  Analytics.logEvent('ExpandProfile', {
    /*
     * We want to know if the user came from from the swipe card as
     * opposed to from chat or a deep link.
     */
    sender: 'card',
    /*
     * This may be too specific and not very useful, but maybe down the line * we could investigate why a certain user is more popular than others.
     */
    user: uid,
    /*
     * We can use this information later to compare against other events.
     */
    screen: 'profile',
    purpose: 'Viewing more info on a user',
  });
};

React Navigation

You can track the screens your users are interacting with by integrating our recommend navigation library: react-navigation. To see an example of how this works, see Screen tracking in React Navigation documentation.

API

import * as Analytics from 'expo-firebase-analytics';
To use web analytics, you'll also need to install the peer dependency firebase with expo install firebase.

Classes

FirebaseAnalyticsJS

A pure JavaScript Google Firebase Analytics implementation that uses the HTTPS Measurement API 2 to send events to Google Analytics.

This class provides an alternative for the Firebase Analytics module shipped with the Firebase JS SDK. That library uses the gtag.js dependency and requires certain browser features. This prevents the use analytics on other platforms, such as Node-js and react-native.

FirebaseAnalyticsJS provides a bare-bone implementation of the new HTTPS Measurement API 2 protocol (which is undocumented), with an API that follows the Firebase Analytics JS SDK.

url

Type: string

clearEvents()

Clears any queued events and cancels the flush timer.

  • Undo-iconvoid

logEvent(eventName, eventParams)

NameTypeDescription
eventNamestring-
eventParams
(optional)
undefined-

https://firebase.google.com/docs/reference/js/firebase.analytics.Analytics#log-event

parseEvent(options, eventName, eventParams)

NameTypeDescription
optionsFirebaseAnalyticsJSOptions-
eventNamestring-
eventParams
(optional)
undefined-

Parses an event (as passed to logEvent) and throws an error when the event-name or parameters are invalid.

Upon success, returns the event in encoded format, ready to be send through the Google Measurement API v2.

parseUserProperty(options, userPropertyName, userPropertyValue)

NameTypeDescription
optionsFirebaseAnalyticsJSOptions-
userPropertyNamestring-
userPropertyValueany-

Parses user-properties (as passed to setUserProperties) and throws an error when one of the user properties is invalid.

Upon success, returns the user-properties in encoded format, ready to be send through the Google Measurement API v2.

  • Undo-iconstring

resetAnalyticsData()

Clears all analytics data for this instance.

setClientId(clientId)

NameTypeDescription
clientIdstring-

Sets a new value for the client ID.

  • Undo-iconvoid

setDebugModeEnabled(isEnabled)

NameTypeDescription
isEnabledboolean-

Enables or disabled debug mode.

setSessionTimeoutDuration(_sessionTimeoutInterval)

NameTypeDescription
_sessionTimeoutIntervalnumber-

Not supported, this method is a no-op

Methods

Analytics.logEvent(name, properties)

NameTypeDescription
namestring

The name of the event. Should contain 1 to 40 alphanumeric characters or underscores. The name must start with an alphabetic character. Some event names are reserved. The firebase_, google_, and ga_ prefixes are reserved and should not be used. Note that event names are case-sensitive and that logging two events whose names differ only in case will result in two distinct events. To manually log screen view events, use the screen_view event name.

properties
(optional)
Record<string, any>

The dictionary of event parameters. Passing undefined indicates that the event has no parameters. Parameter names can be up to 40 characters long and must start with an alphabetic character and contain only alphanumeric characters and underscores. Only String and Number parameter types are supported; and items arrays containing dictionaries. String parameter values can be up to 100 characters long. The firebase_, google_, and ga_ prefixes are reserved and should not be used for parameter names.

Logs an app event. The event can have up to 25 parameters. Events with the same name must have the same parameters. Up to 500 event names are supported. Using predefined events and/or parameters is recommended for optimal reporting. See the Google Analytics event reference for a list of all predefined events.

Info-icon

The following event names are reserved for the native SDKs automatic collection and cannot be used: ad_activeview, ad_click, ad_exposure, ad_query, ad_reward, adunit_exposure, app_background, app_clear_data, app_exception, app_remove, app_store_refund, app_store_subscription_cancel, ad_activeview, ad_click, ad_exposure, ad_query, ad_reward, adunit_exposure, app_background, app_clear_data, app_exception, app_remove, app_store_refund, app_store_subscription_cancel, app_store_subscription_convert, app_store_subscription_renew, app_update, app_upgrade, dynamic_link_app_open, dynamic_link_app_update, dynamic_link_first_open, error, firebase_campaign, first_open, first_visit, in_app_purchase, notification_dismiss, notification_foreground, notification_open, notification_receive, os_update, session_start, session_start_with_rollout, user_engagement

Example

await Analytics.logEvent('add_to_cart', {
  currency: 'USD',
  value: 29.98
  items: [{
    id: "P12345",
    name: "Expo Warhol T-Shirt",
    brand: "Expo",
    category: "Apparel/T-Shirts",
    coupon: "SUMMER_DISCOUNT",
    list_name: "Search Results",
    list_position: 1,
    price: 14.99,
    quantity: 2,
    variant: "Blue"
  }]
});

Analytics.resetAnalyticsData()

Clears all analytics data for this instance from the device and resets the app instance ID.

Analytics.setAnalyticsCollectionEnabled(isEnabled)

NameTypeDescription
isEnabledboolean

A flag that enables or disables Analytics collection.

Sets whether analytics collection is enabled for this app on this device. This setting is persisted across app sessions. By default it is enabled.

Only for:
Expo-go-logoExpo Go

Analytics.setClientId(clientId)

NameTypeDescription
clientIdstring

UUIDv4 string value to set for the current session in Expo Go.

Sets the clientId to the given value. For best results, set this value before calling any other functions on this module.

By default, the clientId is set to Constants.installationId in Expo Go, which is deprecated and will be removed in SDK 44. At that time, this method will need to be used to set the clientId when using Expo Go.

  • Undo-iconvoid
Only for:
Expo-go-logoExpo Go

Analytics.setDebugModeEnabled(isEnabled)

NameTypeDescription
isEnabledboolean

A flag that enables or disables debug mode.

Enables or disabled debug mode on the Expo client, so events can be tracked using the DebugView in the Analytics dashboard.

This option is only available in Expo Go. When using a custom development app, a standalone app, the bare workflow or web, use the natively available options.

Analytics.setSessionTimeoutDuration(sessionTimeoutInterval)

NameTypeDescription
sessionTimeoutIntervalnumber

The custom time of inactivity in milliseconds before the current session terminates.

Sets the interval of inactivity in seconds that terminates the current session. The default value is 1800000 milliseconds (30 minutes).

Info-icon

Setting the session timeout only applies to the native iOS and Android SDKs. Calling this method does nothing on Expo Go or web.

Analytics.setUnavailabilityLogging(isEnabled)

NameTypeDescription
isEnabledboolean

A flag that enables or disables unavailability logging.

Enables or disables the warning and log messages when using Firebase Analytics on the Expo client.

Firebase Analytics is not available on the Expo client and therefore logs the requests to the console for development purposes. To test Firebase Analytics, create a standalone build or custom client. Use this function to suppress the warning and log messages.

  • Undo-iconvoid

Analytics.setUserId(userId)

NameTypeDescription
userIdnull | string

The user ID to ascribe to the user of this app on this device, which must be non-empty and no more than 256 characters long. Setting userID to null removes the user ID.

Sets the user ID property. This feature must be used in accordance with Google's Privacy Policy

Analytics.setUserProperties(properties)

NameTypeDescription
propertiesRecord<string, null | string>

Key/value set of user properties. Values can be up to 36 characters long. Setting the value to null removes the user property.

Sets multiple user properties to the supplied values.

Example

await Analytics.setUserProperties({
  loves_expo: 'a lot',
});

Analytics.setUserProperty(name, value)

NameTypeDescription
namestring

The name of the user property to set. Should contain 1 to 24 alphanumeric characters or underscores and must start with an alphabetic character. The firebase_, google_, and ga_ prefixes are reserved and should not be used for user property names.

valuenull | string

The value of the user property. Values can be up to 36 characters long. Setting the value to null removes the user property.

Sets a user property to a given value. Up to 25 user property names are supported. Once set, user property values persist throughout the app life-cycle and across sessions.

The following user property names are reserved and cannot be used:

  • first_open_time
  • last_deep_link_referrer
  • user_id

Example

await Analytics.setUserProperty('favorite_batmobile', '1989 Burton-mobile');
  • Message-iconAsk a question on the forums about FirebaseAnalytics
  • Github-iconView open bug reports for FirebaseAnalytics
  • Code-iconView source code for FirebaseAnalytics
  • Build-iconView package in npm Registry
  • Edit-iconEdit this page

Was this doc helpful?