React, Firebase, and Google Analytics: How To Set Up and Log Events

Posted by Zain Sajjad on March 16, 2021

GSD

In one of our recent posts, we discussed a number of great web analytics tools for React websites. While all of those tools are awesome in one way or another, Google Analytics with Firebase stands out because of its ability to integrate natively on multiple platforms including React CMS systems. Besides this, Firebase allows you to perform actions based on insights obtained from analytics. For example, you can send push notifications to users with abandoned carts or ones who have availed their last discount. 

React, Firebase, and Google Analytics - Cover Image

Firebase SDK for Android & iOS allows you to integrate analytics in your mobile app while Firebase’s JS SDK does the same for websites. Here we will look into how we can leverage Firebase’s JS SDK in React applications.

Integrating React, Firebase, and Google Analytics

Before we start integrating Firebase with Google Analytics in our application, please make sure you have set up a Firebase application from the console. While creating your project, please make sure to enable Google Analytics for your Firebase app. 

Just to mention, you can add the Firebase JS SDK in your app via npm or yarn;

yarn add firebase

Once you have created a Firebase app on the console, please add the web platform app. Then you will be able to get the Firebase web configs from the project settings.

Screenshot: Firebase project settings

Add the #1 React CMS to your app in minutes.

Initializing Firebase in React

Once you have successfully created the Firebase console’s app and installed the Firebase package, it is now time to initialize Firebase analytics. This initialization triggers the logging of default events that we will discuss later in this post.  Here is how you can do that:

import firebase from 'firebase/app';

let firebaseAnalytics: firebase.analytics.Analytics;

export async function initFirebaseAnalytics(): Promise<
      firebase.analytics.Analytics
    > {
      if (!firebaseAnalytics) {
        await require('firebase/analytics');
        firebaseAnalytics = await firebase.analytics();
      }
      return firebaseAnalytics;
    }

Adding User Properties to Events

One of the top features of Firebase is its ability to attach contextual properties with all of your events, which includes many anonymous properties of users. Firebase attaches a user’s age bracket, gender, and interests. Besides the defaults, you can also set up to 25 different Analytics User Properties per project. This can help us cluster the users of our app based on interests and other associated properties.

undefined

Once you have registered the property in the User Properties page of Analytics in the Firebase console, you’re all set to add a user’s properties to Firebase events using the following code:

firebaseAnalytics.setUserProperties({ is_subscriber: true });

To Be Called When:

  • On every app start whenever a user’s information is available - For example when you have checked a user’s information from an API session or local storage.
  • When a user has logged in or signed up with your app.
  • Resetting all properties to defaults when a user logs out.
  • Any other place where a user’s properties are changed.

Add the #1 React CMS to your app in minutes.

Logging Firebase Events

One of the best advantages of using Firebase analytics is its ability to provide in-depth context of events you have logged. Its ability to log the number of parameters along with events makes it more powerful and useful when it comes to generating actionable insights. We will divide the events into three major sections to help you structure your React app analytics.

firebaseAnalytics.logEvent(EVENT_NAME, PARAMS);

Automatically Logged Events

Firebase has a set of predefined events which enable you to track user journeys and general behaviors in your app. The list of automatically logged events includes events that occur almost in every session or are associated with every use of your app. Here is the full list.

No need to worry about these as Firebase handles these events itself!

Ecommerce Events

Ecommerce is more competitive than ever before. With finite resources, you have to make sure that you’re making the most of every visitor, having the complete stats about how users are navigating through your store is essential. To check drop-off percentage across your sales funnel will definitely tell how good of an experience it is. 

Illustration: Ecommerce events in Firebase

Firebase offers out-of-the-box support for ecommerce businesses and has a set of defined events that you can trigger throughout user journeys. Here is the list of events:

User Navigation

These events will be triggered more often and will let you know what products are being viewed the most.

Event JS Constant To Be Called Parameters
view_item VIEW_ITEM When a user views an item currency, items, value
view_item_list VIEW_ITEM_LIST When a user sees a list of items/offerings items, item_list_name, item_list_id
view_promotion VIEW_PROMOTION When a promotion is shown to a user items, promotion_id, promotion_name, creative_name, creative_slot, location_id
add_to_wishlist ADD_TO_WISHLIST When a user adds items to a favorites currency, items, value
select_item SELECT_ITEM When an item is selected from a list items, item_list_name, item_list_id
select_promotion SELECT_PROMOTION When a user selects a promotion items, promotion_id, promotion_name, creative_name, creative_slot, location_id

Purchase Events

These events help you create closed sales funnels and track a user’s purchase journey.

Event JS Constant To Be Called Parameters
add_to_cart ADD_TO_CART When a user adds items to their cart currency, items, value
remove_from_cart REMOVE_FROM_CART When a user removes items from a cart currency, items, value
view_cart VIEW_CART When a user views their cart currency, items, value
begin_checkout BEGIN_CHECKOUT When a user begins checkout coupon, currency, items, value
add_payment_info ADD_PAYMENT_INFO When a user submits their payment information coupon, currency, items, payment_type, value
add_shipping_info ADD_SHIPPING_INFO When a user submits their shipping information coupon, currency, items, shipping_tier, value
purchase PURCHASE When a user completes a purchase affiliation, coupon, currency, items, transaction_id, shipping, tax, value (required parameter)

Some Other Events

These events help you track a few sideline events.

Event JS Constant To Be Called Parameters
refund REFUND When a refund is issued affiliation, coupon, currency, items, transaction_id, shipping, tax, value
generate_lead GENERATE_LEAD When a user submits a form or request for information value, currency

In order to retrieve maximum output from Firebase, make sure you’re logging all parameters along with events. Bringing in Enhanced Ecommerce can be super helpful for stores to understand conversions better.

Gaming Events

For gaming apps, Firebase Google Analytics has a set of predefined events to know how players are. Here is the full list of events. These events, along with e-commerce events, can help you deliver tailored experiences for each player. 

Illustration: Gaming events in Firebase

Custom Firebase Events

Besides predefined events, you can create 500 custom events. This can be super helpful in tracking a user’s journey for different industries. These events are also logged with all contextual information just like any predefined event. Also, user properties associated with the session will appear with these events. Hence, you have all the required freedom to tailor analytics your way. To be called whenever you feel it’s right. 😉 It’s all your call.

Performing Actions: Cloud Functions, Messaging, and Remote Configuration

Firebase Analytics is not just about getting reports about user behaviors in your app, rather it helps you perform actions using the insight you receive from an analytics implementation. Let’s consider a few examples: 

  • Send a special promo code to all users with abandoned carts. Firebase Analytics integrated with Firebase Cloud Function can help you achieve this easily.
  • Send push notifications to all purchasers about new arrivals. You can easily create a user audience for Firebase Cloud Messaging based on user properties and analytics events; hence FCM will deliver notifications to only relevant customers.
  • Customize experiences for premium users. With the help of Firebase Remote Configs, this can be done with ease.

More Insights: Using BigQuery

BigQuery is a serverless, highly scalable, and cost-effective multi-cloud data warehouse designed for business agility. All of the events you log in Firebase analytics can be stored in BigQuery; hence making it more fun to generate in-depth reports and produce actionable insights. As mentioned earlier as well, Firebase itself associates contextual information with your events. All of this contextual information, which includes geolocation, device information, and much more, is stored with each event in a BigQuery warehouse and can be queried using simple SQL—in a fraction of the time.

On top of that, the BigQuery BI Engine seamlessly integrates with familiar tools like Data Studio and will help accelerate data exploration and analysis. Also, BigQuery ML enables data scientists and data analysts to build and operationalize ML models on planet-scale structured or semi-structured data, directly inside BigQuery.

Conclusion

Google Analytics for Firebase opens up a whole new stream of amazing features that you can integrate into your application to make it more awesome. It works seamlessly with popular React CMS systems like ButterCMS. It can also help you generate more revenue and sales. If implemented to its fullest extent, Firebase with Google Analytics can have a huge impact on the growth of your business.

 

Sign up to receive more articles about ButterCMS and React.
    
Zain Sajjad

Zain is a Senior Frontend Engineer at Peekaboo Guru. He is passionate about anything and everything React, React Native, JavaScript & Mobile Machine Learning.

ButterCMS is the #1 rated Headless CMS

Related articles

Don’t miss a single post

Get our latest articles, stay updated!