SDKs overview

Google Analytics offers a range of Software Development Kits (SDKs) and libraries designed to facilitate the collection, measurement, and reporting of user interactions across various digital properties. The primary focus of these tools is to enable developers to implement Google Analytics 4 (GA4), the current generation of Google Analytics, which uses an event-based data model. These SDKs and libraries streamline the process of sending data to Google Analytics, whether from websites, mobile applications, or server-side environments.

For web properties, the core components include the Google tag (gtag.js) for direct JavaScript implementation and Google Tag Manager (GTM) for a more flexible, tag-based deployment. Mobile applications leverage Firebase SDKs, which provide a unified analytics solution for both iOS and Android. Beyond client-side data collection, Google Analytics also provides server-side APIs, such as the Google Analytics Data API, for programmatic access to reporting data, enabling custom analytics solutions and integrations with other systems. These APIs allow developers to build dashboards, automate reporting, and integrate analytics data into business intelligence tools Google Analytics reporting API documentation.

The choice of SDK or library depends on the platform and specific implementation needs. While Google provides official tools for core functionalities, the community also contributes various wrappers and extensions, particularly for server-side languages or specific frameworks.

Official SDKs by language

Google provides several official methods for integrating Google Analytics into applications and websites, primarily through JavaScript-based tags for web properties and Firebase SDKs for mobile applications. For server-side interactions, various Google client libraries exist to access the Google Analytics Data API.

Web (JavaScript)

The main official SDK for web properties is the Google tag (gtag.js). This JavaScript library allows direct implementation of analytics tracking by adding a snippet to the website's HTML. It supports sending events to Google Analytics, Google Ads, and other Google products. Alternatively, Google Tag Manager provides a container to manage all tags, including the Google tag, without modifying website code directly for each change Google Tag Manager overview.

Mobile (Firebase SDKs)

For iOS and Android applications, Google Analytics 4 integrates with Firebase. The Firebase SDKs provide comprehensive analytics capabilities for mobile apps, including automatic event collection and custom event logging. These SDKs are available for multiple platforms beyond just native mobile development.

The following table summarizes the key official SDKs and their primary uses:

Platform/Language Package/Method Primary Use Maturity
Web (JavaScript) Google tag (gtag.js) Direct website tracking, event collection Stable
Web (JavaScript) Google Tag Manager (GTM) Tag management, flexible deployment of analytics Stable
iOS Firebase SDK for Google Analytics iOS app analytics, event collection Stable
Android Firebase SDK for Google Analytics Android app analytics, event collection Stable
Flutter firebase_analytics plugin Flutter app analytics via Firebase Stable
React Native @react-native-firebase/analytics React Native app analytics via Firebase Stable
Unity Firebase Unity SDK Unity game analytics, event collection Stable
C++ Firebase C++ SDK C++ game/app analytics, event collection Stable
Python Google API Client Library for Python Accessing Google Analytics Data API Stable
Java Google API Client Library for Java Accessing Google Analytics Data API Stable
Node.js Google API Client Library for Node.js Accessing Google Analytics Data API Stable

Installation

The installation process varies significantly based on the platform and chosen method (direct JavaScript, Tag Manager, or Firebase SDKs).

Web (Google tag - gtag.js)

To install the Google tag, you insert a JavaScript snippet into the <head> section of every page on your website. This snippet initializes the tag and allows it to send data to your Google Analytics 4 property.

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX');
</script>

Replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID Google Analytics 4 setup guide. After placing this code, basic page view data will be collected automatically.

Web (Google Tag Manager)

For Google Tag Manager, you embed two snippets of code on your website: one in the <head> and one after the opening <body> tag. All Google Analytics configuration is then done within the GTM interface, allowing marketers and developers to manage tags without code changes to the site.

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXXX');</script>
<!-- End Google Tag Manager -->
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Replace GTM-XXXXXXX with your Google Tag Manager Container ID Google Tag Manager installation guide. Within the GTM interface, you would then configure a Google Analytics 4 Configuration Tag.

Mobile (Firebase SDKs)

For mobile applications, Firebase SDKs are integrated into your app project. This typically involves adding dependencies to your project's build configuration (e.g., build.gradle for Android, Podfile for iOS) and then initializing Firebase within your app's code. Detailed instructions are available for specific platforms.

Android (build.gradle)

dependencies {
    implementation 'com.google.firebase:firebase-analytics'
    // Add the Firebase BoM to manage your Analytics version
    implementation platform('com.google.firebase:firebase-bom:32.7.4')
}

iOS (Podfile)

pod 'Firebase/Analytics'

After adding the dependency, you would run pod install or sync your Gradle project. For comprehensive setup details on Firebase for different platforms, refer to the Firebase Analytics getting started guide.

Server-Side (Google Analytics Data API Client Libraries)

For accessing reporting data programmatically, you'll use Google's client libraries for various server-side languages. Installation usually involves a package manager:

Python

pip install google-analytics-data

Node.js

npm install @google-analytics/data

These libraries require API credentials (e.g., service account keys) and proper authentication to make requests to the Google Analytics Data API Google Analytics Data API client library quickstart.

Quickstart example

This example demonstrates how to send a custom event to Google Analytics 4 using the gtag.js snippet on a web page. This is a common task for tracking specific user interactions beyond standard page views.

Web (JavaScript - gtag.js Custom Event)

First, ensure the basic Google tag snippet is installed in your page's <head> as described in the installation section. Then, you can call the gtag() function to send custom events. This example tracks a 'level_up' event in a game context.

// Assuming gtag.js is already loaded and configured with your Measurement ID 'G-XXXXXXXXXX'

// Function to simulate a user leveling up
function userLeveledUp(levelNumber, characterName) {
  gtag('event', 'level_up', {
    'level': levelNumber,
    'character_name': characterName
  });
  console.log(`Sent 'level_up' event for ${characterName} at level ${levelNumber}`);
}

// Example usage: call this function when a user levels up
document.getElementById('levelUpButton').addEventListener('click', function() {
  userLeveledUp(5, 'Hero');
});

// Another example usage, perhaps after an async operation
setTimeout(() => {
  userLeveledUp(6, 'Hero');
}, 3000);

This code defines a function userLeveledUp that sends an event named 'level_up' with two custom parameters: level and character_name. These parameters provide additional context to the event, which can be analyzed in Google Analytics gtag.js event documentation. You would typically trigger such events based on specific user actions, like button clicks, form submissions, or video plays.

Mobile (Firebase Analytics for Android - Custom Event)

This example demonstrates how to log a custom event using the Firebase Analytics SDK in an Android application. This is equivalent to the web example but for a mobile context.

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {

    private FirebaseAnalytics mFirebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Firebase Analytics
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        // Example: Log a custom event when a button is clicked
        findViewById(R.id.my_button).setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putInt(FirebaseAnalytics.Param.LEVEL, 5);
            bundle.putString(FirebaseAnalytics.Param.CHARACTER, "Hero");
            mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.LEVEL_UP, bundle);
            // Using pre-defined FirebaseAnalytics.Event and Param for better consistency
            // For truly custom events, use custom strings for event name and parameters
            // For example: mFirebaseAnalytics.logEvent("my_custom_event", customBundle);
            System.out.println("Logged 'level_up' event via Firebase Analytics");
        });
    }
}

In this Android example, after initializing FirebaseAnalytics, a custom 'level_up' event is logged with associated parameters LEVEL and CHARACTER. Firebase provides a set of recommended events and parameters for common use cases, which developers should prioritize. For unique requirements, custom event names and parameters can be defined.

Community libraries

While Google provides official SDKs and client libraries, the developer community often creates additional tools, wrappers, and integrations that can simplify working with Google Analytics, especially for specific frameworks or languages where an official client library might be more general-purpose.

  • Client-side Framework Integrations: For popular JavaScript frameworks like React, Angular, and Vue.js, community packages often provide components or hooks that abstract away the direct gtag.js calls. These libraries can simplify event tracking within the component lifecycle or integrate with the framework's routing system. Examples include react-ga4 for React applications, which offers a more idiomatic way to initialize and send events to GA4.
  • Server-Side Language Wrappers: Although Google provides official client libraries for its APIs (like the Google Analytics Data API), community-maintained wrappers or SDKs may offer a more tailored experience for specific server-side languages or frameworks. For instance, some developers might create simpler HTTP clients in PHP or Ruby that wrap the official API calls for basic reporting tasks, although these often build upon or interact with Google's official REST API specifications Google Analytics Data API REST reference.
  • Content Management System (CMS) Plugins: Many CMS platforms like WordPress, Drupal, and Joomla have plugins developed by the community that integrate Google Analytics tracking. These plugins often allow users to input their Measurement ID and configure basic tracking settings without writing any code. Some advanced plugins may offer features like enhanced e-commerce tracking or custom dimension/metric setup directly from the CMS admin interface. Such plugins often abstract the gtag.js or Google Tag Manager implementation details.
  • Testing and Debugging Tools: Beyond data collection, the community also contributes tools for testing and debugging Google Analytics implementations. While Google offers the Tag Assistant Companion for browsers, third-party browser extensions or local development tools might provide additional insights into data layer contents or event processing, helping ensure accurate data collection.

When considering community libraries, it is important to evaluate their maintenance status, community support, and alignment with Google's latest analytics recommendations, especially with the continuous evolution of Google Analytics 4. A reputable source for evaluating open-source libraries is GitHub, where developers can inspect code, review issue trackers, and assess contribution frequency. It is also beneficial to check if the library is actively maintained and compatible with the latest Google Analytics API versions.

The Python Package Index (PyPI) is another resource for finding community-contributed Python libraries related to Google Analytics, often focusing on reporting and data manipulation. For example, libraries might exist to simplify authentication or data extraction from the Google Analytics Data API, providing a higher-level abstraction than the official Google API Client Library for Python. Similarly, npm for Node.js projects hosts various community packages, some of which interact with Google Analytics.