Back to Insights
Data Engineering 8/8/2024 5 min read

Real-time Feature Flags & Dynamic Config for Server-Side GA4 with Firestore and Cloud Run

Real-time Feature Flags & Dynamic Config for Server-Side GA4 with Firestore and Cloud Run

You've mastered the art of building a robust server-side Google Analytics 4 (GA4) pipeline. You're enriching events with valuable user and product data from BigQuery, enforcing data quality, managing granular consent, and activating insights – all orchestrated by Google Tag Manager (GTM) Server Container on Cloud Run. This architecture provides unparalleled control and data quality.

However, a common challenge emerges: how do you manage dynamic configurations, A/B test variations, or feature flags that need to be updated frequently and reflected in your analytics in real-time, with minimal latency?

The existing approach of using BigQuery for enrichment, while powerful for large, relatively static datasets, isn't ideal for dynamic, low-latency lookups. Changing a feature flag often means updating a BigQuery table (which might have replication delay), or worse, redeploying your custom Cloud Run enrichment service or even your GTM Server Container for simple configuration changes. This process is cumbersome, introduces unnecessary deployment cycles, and slows down your marketing and product teams' ability to iterate.

The problem is the need for a fast, lightweight, and easily updatable real-time configuration store that your server-side GA4 pipeline can query on demand.

The Solution: Firestore for Dynamic Configuration & Feature Flags

Our solution introduces Firestore as a real-time, low-latency configuration and feature flag store, accessible via a dedicated, lightweight Python service on Cloud Run from your GTM Server Container. This allows you to:

  • Dynamically control feature flags: Enable or disable features for specific user segments, geographies, or devices, and track their impact in GA4 immediately.
  • Implement A/B test variations: Assign users to test groups server-side and log the variations to GA4 without modifying client-side code or redeploying your GTM SC.
  • Deliver personalized content: Fetch real-time content recommendations or dynamic pricing tiers based on immediate context.
  • Update configurations instantly: Marketing or product teams can update a configuration in Firestore, and those changes are reflected in your server-side GA4 data within milliseconds.

This approach provides a powerful mechanism for agile experimentation and personalization, seamlessly integrated into your privacy-aware, server-side data pipeline.

Our Extended Architecture: Integrating Firestore for Real-time Lookups

We'll augment our existing server-side GA4 architecture by adding a new Cloud Run service specifically designed to interact with Firestore. This service will act as a bridge, fetching dynamic configurations or feature flags, and returning them to the GTM Server Container to enrich the event before it's sent to GA4.

graph TD
    A[Browser/Client-Side] -->|1. Raw Event (Data, Consent State)| B(GTM Web Container);
    B -->|2. HTTP Request to GTM Server Container Endpoint| C(GTM Server Container on Cloud Run);\n    (Already deployed)
    C --> D{3. GTM SC Client Processes Event};\n    (Consent & Data Quality Layers)
    D --> E[4. Custom Tag/Variable: Call Dynamic Config Service];
    E -->|5. HTTP Request with User/Context Data| F[Dynamic Config Service (Python on Cloud Run)];\n    (New Service)
    F -->|6. Real-time Lookup| G[Firestore (Feature Flags, A/B Test Config)];\n    (New Component)
    G -->|7. Return Dynamic Data| F;
    F -->|8. Return Configured/Enriched Event Data| E;
    E -->|9. Add Dynamic Data to Event| D;
    D -->|10. Consent Check & Dispatch to GA4 Measurement Protocol| H[Google Analytics 4];
    D -->|Optional: Call BigQuery Enrichment (existing)| I[Existing BigQuery Enrichment Service];
    I --> J[BigQuery (Static User/Product Data)];

Core Components Deep Dive & Implementation Steps

1. Firestore Setup: Your Real-time Configuration Store

Firestore is a NoSQL document database, perfect for storing JSON-like configuration objects with low latency.

a. Create a Firestore Database:

  1. In the GCP Console, navigate to Firestore.
  2. Choose "Native mode" (or Datastore mode if you prefer).
  3. Select a region that is geographically close to your Cloud Run services for optimal performance.

b. Structure Your Configuration Data: Create collections and documents to store your feature flags or A/B test configurations.

Example: feature_flags collection

| Collection: feature_flags | | | :-------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------_ . The items array of your GA4 event data in the GTM Server Container holds valuable information.

  • Accessing Item Data:

    • To get a specific item's property: getEventData('items.0.item_id') (for the first item's ID).
    • To get the entire items array: getEventData('items').
  • Adding/Modifying Item Data:

    • To add a new property to the first item: setInEventData('items.0.new_property', 'someValue', true).
    • To replace the entire items array: setInEventData('items', newItemsArray, true).

Example Scenario: Adding a product_view_position to items after a view_item_list event

Let's say your client-side pushes a view_item_list event, and you want to enrich each item in the items array with its position within the list before it gets sent to GA4. This isn't usually sent client-side for items within view_item_list.

const getEventData = require('getEventData');
const setInEventData = require('setInEventData');
const log = require('log');

// Configuration fields for the template:
//   - targetEventName: Text input for the event to target (e.g., 'view_item_list')

const eventName = getEventData('event_name');

if (eventName === data.targetEventName) {
    const items = getEventData('items');

    if (items && Array.isArray(items)) {
        log(`Processing ${items.length} items for event '${eventName}'.`, 'INFO');
        const updatedItems = items.map((item, index) => {
            if (item && typeof item === 'object') {
                // Add a new property 'item_list_position'
                return { ...item, item_list_position: index + 1 };
            }
            return item;
        });

        // Replace the original 'items' array with the updated one
        setInEventData('items', updatedItems, true);
        log('Items array enriched with item_list_position.', 'INFO');
    } else {
        log(`No valid 'items' array found for event '${eventName}'.`, 'WARNING');
    }
} else {
    log(`Skipping item enrichment for event '${eventName}'. Target is '${data.targetEventName}'.`, 'DEBUG');
}

data.gtmOnSuccess();

Implementation in GTM Server Container:

  1. Create a new Custom Tag Template named "Item List Position Enrichet".
  2. Paste the code and add Access event data permission.
  3. Create a Custom Tag using this template.
  4. Configure targetEventName to 'view_item_list'.
  5. Set the trigger for this tag to Custom Event where Event Name equals view_item_list. Ensure this tag fires before your GA4 event tag for view_item_list.

After this tag fires, the items array in the event data will have an additional item_list_position property for each item. This enriched data will then be sent to GA4 when your GA4 event tag fires.

Advanced Item Processing: Filtering & Aggregation

You can also use custom templates to filter out items that don't meet certain criteria or to aggregate item-level data into event-level summaries.

Example Scenario: Removing "Invalid" Items and Calculating Total Quantity

Suppose your client-side pushes items where some might have item_id as null or undefined due to tracking errors. You want to remove these invalid items and calculate the total quantity of valid items.

const getEventData = require('getEventData');
const setInEventData = require('setInEventData');
const log = require('log');

// Configuration fields for the template:
//   - targetEventName: Text input for the event to target (e.g., 'add_to_cart', 'purchase')

const eventName = getEventData('event_name');

if (eventName === data.targetEventName) {
    const items = getEventData('items');

    if (items && Array.isArray(items)) {
        let totalValidQuantity = 0;
        const validItems = [];

        for (const item of items) {
            // Define criteria for a "valid" item (e.g., must have an item_id)
            if (item && item.item_id) {
                validItems.push(item);
                // Aggregate quantity, defaulting to 1 if not present
                totalValidQuantity += (item.quantity && typeof item.quantity === 'number') ? item.quantity : 1;
            } else {
                log(`Invalid item found in event '${eventName}', item_id missing:`, item, 'WARNING');
            }
        }

        // Replace the items array with only valid items
        setInEventData('items', validItems, true);
        log(`Filtered items for event '${eventName}'. Valid items: ${validItems.length}`, 'INFO');

        // Add total valid quantity as an event parameter
        setInEventData('total_valid_quantity', totalValidQuantity, true);
        log(`Added total_valid_quantity: ${totalValidQuantity} to event '${eventName}'.`, 'INFO');

    } else {
        log(`No valid 'items' array found for event '${eventName}'.`, 'WARNING');
    }
} else {
    log(`Skipping item processing for event '${eventName}'. Target is '${data.targetEventName}'.`, 'DEBUG');
}

data.gtmOnSuccess();

Implementation in GTM Server Container:

  1. Create a new Custom Tag Template named "Item Filter & Aggregator".
  2. Paste the code and add Access event data permission.
  3. Create a Custom Tag using this template.
  4. Configure targetEventName (e.g., 'add_to_cart', 'purchase').
  5. Set the trigger for this tag to Custom Event where Event Name matches your configured event names. Ensure this tag fires before your GA4 event tag.

This example demonstrates how you can clean your item data and derive new metrics (total_valid_quantity) before sending it to GA4, ensuring higher data quality and providing immediate aggregate insights.

Benefits of Item-Level Transformations in GTM Server Container

  • Enhanced Data Quality: Clean, standardize, and validate item data before it reaches GA4, preventing reporting errors.
  • Richer Insights: Add calculated properties, standardize categories, or apply business logic at the item level that isn't feasible client-side.
  • Reduced Client-Side Complexity: Offload complex item manipulation logic from the browser to the server, improving page load performance and reducing client-side code bloat.
  • Centralized Control: Apply consistent item processing rules across all your tracking implementations from a single, controlled environment.
  • Compliance & Privacy: Easily filter out sensitive item data or ensure specific item-level parameters adhere to privacy guidelines.

Conclusion

While focusing on event-level and user-level data is crucial, the items array in GA4 events holds a wealth of detailed product interaction information. By leveraging the power of GTM Server Container custom templates on Cloud Run, you can unlock a new dimension of control and precision over this critical data. From dynamically adding positions to filtering invalid entries and aggregating quantities, server-side item transformations empower you to send cleaner, richer, and more actionable item-level data to GA4, driving deeper product and e-commerce insights. Embrace these capabilities to elevate your analytics data quality and strategic decision-making.