GSD

React Firebase Analytics: Setting Up and Logging Events with Google Analytics

Posted by Zain Sajjad on May 14, 2024

Within a decade of release, React has become the go-to JavaScript library for developing web applications. Today, we will explore how to set up a React app for analytics with Firebase and Google Analytics 4 (GA 4). Firebase is a mobile and app development platform from Google, whereas GA4 is the latest iteration of Google’s analytics platform. 

Out of all the great web analytics tools for React apps, the GA 4 and Firebase combo stands out because it can 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. 

Firebase SDKs for Android, iOS, and JavaScript make it easy to integrate React Firebase analytics into mobile apps and websites. Here, we will focus on leveraging the JavaScript SDK for React-powered websites.

Why integrate Firebase with GA4?

Firebase offers a suite of backend services for mobile and web app development. One of its key features is the native integration with Google Analytics 4. This allows developers to set up React Firebase analytics with GA 4 easily. Here are some reasons why this is so beneficial:

  • Using Firebase analytics React JS, you can capture user interactions (events) in your React app with minimal code. This data is then seamlessly transferred to GA4 for comprehensive analysis in a user-friendly platform.

  • Track user behavior across platforms (web and mobile) using a single platform, GA4. This allows you to have a holistic view of the user journey without having to manage separate analytics tools for web, mobile, and other apps.

  • With Firebase's powerful features like Remote Config, A/B Testing, and Cloud Messaging combined with GA4's advanced event tracking offerings, you can gain deeper insights into user engagement and optimize your app accordingly.

  • GA4's powerful segmentation and audience creation features allow you to identify specific user groups based on their in-app behavior. Moreover, predictive metrics in GA4 help you discern user patterns and predict future behavior. This translates into the ability to create finely tailored and personalized marketing campaigns.

Google Analytics Universal vs. Google Analytics 4

Google Analytics 4 introduces a lot of improvements and new features that weren’t present in Google Analytics Universal. Here are some examples:

  • GA4 has an event-based tracking model, which shifts the focus from pageviews to user interactions. This change makes it easy to capture interactions in React apps and send them as events to GA4.

  • GA 4 offers features like user deletion and data anonymization to ensure that user privacy is a top priority. This aligns with the increasing focus on data privacy regulations worldwide.

  • GA4 leverages machine learning to automatically fill data gaps, identify trends, and provide predictive insights. 

  • Mobile app data collection has been made significantly easier. Once you add the Google Analytics for Firebase (GA4F) SDK to your app, a large number of events start getting captured and aggregated automatically. 

  • GA 4 is also more interoperable. For example, with Universal, you’d need a GA 360 account to integrate analytics with BigQuery. With GA 4, this integration is available for free. This means you can easily integrate your Firebase analytics React app with BigQuery to analyze your data more comprehensively.

So, where does React fit in?

So far, we've discussed the power of Firebase Analytics and GA4 for gathering user insights. But why are we specifically focusing on React in this context? Well, React is perfect for our modern analytics setup for several reasons, including:

  • Like Firebase and GA4, React is a cutting-edge technology built for the present web development landscape. Its component-based architecture promotes code reusability, maintainability, and a simplified development experience. This aligns well with the focus on efficiency and scalability that both Firebase and GA4 place.

  • React’s declarative syntax and vast ecosystem of tools and libraries make it easy to get started and build engaging user experiences. The Google Analytics for Firebase (GA4F) SDK echoes this ease of use, making integration as simple as calling two built-in functions.

  • React's component-based architecture makes it ideal for building data-driven applications.  Components can be easily updated based on user data retrieved from Firebase Analytics and GA4. 

Integrating React, Firebase, and Google Analytics

Before we start integrating Firebase with Google Analytics in our application, please ensure you have set up a Firebase application from the console. While creating the project for Firebase Analytics React js, make sure that you select the “Enable Google Analytics for this project” option. See below:

React firebase analytics: Select google analytics for this project.

After you have created the Firebase Google Analytics project, you will need to register your web app with the project. Follow these steps to do so:

From the main project screen, select the “Web” option:

React firebase analytics: Select the web option

Give your app a name and then click “Register app.”

As instructed by the setup wizard, run the following command to set up Firebase for your app:

npm install firebase

Setup wizard firebase sdk

If you chose to use the Firebase hosting, install the Firebase CLI:

npm install -g firebase-tools

If you didn’t choose the Firebase hosting, you can skip this step.

Again, if you chose Firebase hosting, follow the on-screen steps to run the three commands (see below) and deploy to the hosting. Otherwise, you can skip this step.

Deploy to firebase

Once done, select “Click to console.”

Using React? Why Not Build a Blog? Follow Our Detailed Guide!
Read now

Initializing Firebase in React

Once you have successfully created the Firebase console app and installed the Firebase package, it is time to initialize Firebase analytics. This initialization triggers the logging of default events, which we will discuss later in this post.  

To initialize Firebase analytics Reactjs for your project, you need a set of Firebase configuration parameters associated with your app. To fetch them, go to the project settings on the Firebase dashboard, and scroll down to the “SDK setup and configuration” section inside the “Your apps” tab. Here, you will see a configuration block looking like this:

const firebaseConfig = {

  apiKey: "api-key-here",

  authDomain: "app-firebaseapp.com",

  projectId: "test-id",

  storageBucket: "test-id.appspot.com",

  messagingSenderId: "sender-id-here",

  appId: "app-id-here"

};

The configuration block contains several parameters that allow Firebase to connect to your specific project and authenticate requests. For example, “apiKey” is a unique identifier for your Firebase project that enables API access, and “authDomain” is the domain name used for Firebase Authentication services within your project.

Now that you have the configuration block, you can initialize Firebase as follows:

import { initializeApp } from 'firebase/app';
import { getAnalytics, logEvent } from "firebase/analytics";
//your configuration below
const firebaseConfig = {

  apiKey: "api-key-here",

  authDomain: "app-firebaseapp.com",

  projectId: "test-id",

  storageBucket: "test-id.appspot.com",

  messagingSenderId: "sender-id-here",

  appId: "app-id-here"

};
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

Remember to replace the sample config block above with your config block. The code configures and initializes Firebase and then gets a reference to the analytics service. 

Adding user properties to events

One of Firebase's top features is its ability to attach contextual properties to all of your events, including 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. 

Here's how to go about it:

  1. Navigate to the “Custom Definitions” page from the Analytics section of the Firebase console.

  2. Define a new custom definition for the user property. 

  3. Now, you can add a user’s properties to Firebase using the setUserProperties() method. For example:

const analytics = getAnalytics();
setUserProperties(analytics, { hobby: 'football' });

In the above example, we're setting a user property called "hobby" with the value "football."

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.

  • 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

Using React? Why Not Build a Blog? Follow Our Detailed Guide!
Read now

Logging Firebase Events

One of the best advantages of using Firebase analytics is its ability to provide in-depth context for logged events. Its ability to log the number of parameters along with events makes it more powerful and useful for 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);

The above line of code generates a Google Analytics event with the specified name and parameters.

Automatically logged events

Firebase has a set of predefined events that enable you to track user journeys and general behaviors in your app. The list of automatically logged events includes events that occur in almost 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

The e-commerce landscape is fiercely competitive. Every website visitor represents a valuable opportunity, but you need a deep understanding of user behavior to maximize conversions. By tracking user behavior throughout their shopping experience, you can identify areas for improvement and refine your sales funnel accordingly.

For example, you may analyze drop-off rates at different stages, from product discovery to checkout. High drop-off percentages at specific points can indicate friction or confusion in the user journey.

Illustration: Ecommerce events in Firebase

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

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

sign_up

SIGN_UP

When a user signs up

method (method used for sign up)

view_search_results

VIEW_SEARCH_RESULTS

When a user has been presented with some search results

search_term

To retrieve maximum output from Firebase, make sure you log all parameters along with events. Adding enhanced e-commerce can help stores better understand conversions.

Gaming Events

For gaming apps, Firebase Google Analytics has a set of predefined events designed to track player interactions and behaviors. Here is the complete list of events. These events, along with e-commerce events, can help you deliver tailored experiences for each player. 

Illustration: Gaming events in Firebase

Event

To Be Called

Parameters

earn_virtual_currency

When a user wins some virtual currency

virtual_currency_name, value

level_end

When a user has reached the end of a specific level

level_name, success

level_start

When a user starts a new level

level_name

spend_virtual_currency

When a user spends some of their earned virtual currency

value, virtual_currency_name, item_name

unlock_achievement

When a user unlocks a new achievement

achievement_id

post_score

When a user posts a score

score, level, character

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. 😉 

For example, here are some custom events you could add:

  • Tutorial skipped: Records when a player skips the game tutorial. It can be a good way to gauge the effectiveness of the onboarding process.

  • Power-up used: Capture when a player uses a specific power-up within the game.

  • Product compared: Records when a user compares two or more products. This data can reveal which products are often considered together and inform product placement strategies.

  • Subscription renewed: Logs when a user renews a subscription.

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, making it more fun to generate in-depth reports and produce actionable insights. As mentioned earlier, Firebase 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

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

Post updated May 2024 by Maab Saleem.

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

G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award G2 crowd review award

Don’t miss a single post

Get our latest articles, stay updated!