Skip to main content

Google Analytics 4

Track feature flag usage in Google Analytics 4 for advanced analytics and user behavior correlation.

Overview​

The Toggly GA4 Hook automatically sends feature flag events to Google Analytics 4, allowing you to:

  • Track feature flag usage as GA4 events
  • Correlate features with user behavior in GA4 reports
  • Set user properties for feature flag states
  • Analyze A/B test results with GA4's built-in analysis tools
  • Build audiences based on feature flag exposure
  • Monitor real-time feature changes via GA4 events

Installation​

npm install @ops-ai/toggly-ga4-hook

Prerequisites​

  1. Toggly SDK - Any JavaScript-based Toggly SDK with hooks support (v1.0.0+)
  2. Google Analytics 4 - GA4 tracking code (gtag.js) must be loaded on your page

Quick Start​

import { Toggly } from '@ops-ai/feature-flags-toggly';
import { GA4Hook } from '@ops-ai/toggly-ga4-hook';

Toggly.init({
appKey: 'your-app-key',
environment: 'Production',
hooks: [
new GA4Hook({
measurementId: 'G-XXXXXXXXXX',
trackEvaluations: true,
trackChanges: true,
setUserProperties: true,
})
]
});

Configuration Options​

OptionTypeDefaultDescription
enabledbooleantrueEnable or disable the hook entirely
measurementIdstring-GA4 Measurement ID (optional, uses default gtag)
evaluationEventNamestring"feature_flag_evaluated"Custom event name for evaluations
changeEventNamestring"feature_flag_changed"Custom event name for changes
trackEvaluationsbooleantrueTrack feature flag evaluations
trackAllResultsbooleantrueTrack both true and false results
setUserPropertiesbooleanfalseSet GA4 user properties for features
userPropertyPrefixstring"ff_"Prefix for user property names
trackChangesbooleantrueTrack real-time feature changes
trackIdentitybooleantrueSet user_id in GA4
customParametersobject{}Custom parameters for all events
checkConsentfunction() => trueConsent check callback
debugbooleanfalseEnable debug logging

Full Configuration Example​

const ga4Hook = new GA4Hook({
enabled: process.env.NODE_ENV === 'production',
measurementId: 'G-XXXXXXXXXX',
evaluationEventName: 'ff_evaluated',
changeEventName: 'ff_changed',
trackEvaluations: true,
trackAllResults: true,
setUserProperties: true,
userPropertyPrefix: 'feature_',
trackChanges: true,
trackIdentity: true,
customParameters: {
app_version: '2.0.0',
environment: 'production'
},
checkConsent: () => {
return window.cookieConsent?.analytics ?? false;
},
debug: false
});

What Gets Tracked​

Feature Evaluations​

When a feature flag is evaluated:

gtag('event', 'feature_flag_evaluated', {
feature_key: 'new-checkout-flow',
feature_enabled: true,
event_category: 'toggly'
});

Feature Changes (Real-time)​

When a feature flag state changes via WebSocket:

gtag('event', 'feature_flag_changed', {
feature_key: 'dark-mode',
old_value: false,
new_value: true,
event_category: 'toggly'
});

User Properties​

When setUserProperties: true:

gtag('set', 'user_properties', {
ff_dark_mode: 'on',
ff_new_checkout: 'off'
});

User Identity​

When identity is set in Toggly:

gtag('config', 'G-XXXXXXXXXX', {
user_id: '[email protected]'
});

Framework Examples​

import { createTogglyProvider } from '@ops-ai/react-feature-flags-toggly';
import { GA4Hook } from '@ops-ai/toggly-ga4-hook';

const TogglyProvider = await createTogglyProvider({
appKey: process.env.REACT_APP_TOGGLY_KEY,
environment: 'Production',
hooks: [
new GA4Hook({
measurementId: 'G-XXXXXXXXXX',
setUserProperties: true,
})
]
});

export default function App() {
return (
<TogglyProvider>
<Routes />
</TogglyProvider>
);
}

Viewing Data in GA4​

Custom Events​

  1. Go to GA4 Admin → Events
  2. Look for feature_flag_evaluated and feature_flag_changed
  3. Events appear automatically after first trigger

Event Parameters​

In Explore → Free Form:

  • Add feature_key as a dimension
  • Add feature_enabled as a dimension
  • Analyze feature flag usage patterns

User Properties​

  1. Go to GA4 Admin → Custom definitions → Custom user scopes
  2. Create custom dimensions for ff_* properties
  3. Use in reports to segment by feature flag exposure

Building Audiences​

Create audiences based on feature exposure:

  1. Go to GA4 Admin → Audiences → New audience
  2. Add condition: Event = feature_flag_evaluated
  3. Add parameter condition: feature_key equals your-feature
  4. Add parameter condition: feature_enabled equals true

GDPR/CCPA Compliance​

The checkConsent callback allows integration with consent management platforms:

// OneTrust example
new GA4Hook({
checkConsent: () => window.OneTrust?.IsAlertBoxClosed() &&
window.OneTrust?.GetDomainData()?.Groups
?.find(g => g.CustomGroupId === 'C0002')?.Status === 'active'
});

// Google Consent Mode v2
new GA4Hook({
checkConsent: () => {
return window.dataLayer?.some(item =>
item[0] === 'consent' &&
item[1] === 'update' &&
item[2]?.analytics_storage === 'granted'
) ?? false;
}
});

What data is sent​

  • Feature flag key name (e.g., "dark-mode")
  • Feature evaluation result (true / false)
  • Custom parameters you explicitly configure
  • User ID (only if trackIdentity is enabled and identity is set)
  • No automatic PII collection

Error Handling​

The hook is designed to never break the Toggly SDK:

  • All gtag API calls are wrapped in try-catch
  • If gtag is not loaded, events are silently skipped
  • If gtag throws an error, it is caught and logged to console
  • The hook provides a console warning (not error) if gtag is not detected at initialization

Troubleshooting​

Events not appearing in GA4​

  1. Check gtag is loaded: Ensure the GA4 tracking code is on the page before Toggly initializes

    console.log('gtag available:', typeof window.gtag === 'function');
  2. Check measurement ID: Verify your measurement ID is correct (format: G-XXXXXXXXXX)

  3. Check consent: Verify your checkConsent callback returns true

  4. Enable debug mode:

    new GA4Hook({ debug: true })
  5. Use GA4 DebugView: Enable GA4 debug mode to see events in real-time

    gtag('config', 'G-XXXXXXXXXX', { debug_mode: true });

Console warning at startup​

[Toggly GA4 Hook] Google Analytics 4 gtag not detected.

This means gtag was not loaded when the hook was created. The hook will automatically start sending events once gtag becomes available.