'How to setup custom event tracking with new Google Analytics (GA4) on the server?

I would like to send event data to Google analytics 4 to track conversions on my web app. I found this article: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#send_an_event

First I made a custom event that looks like this: Custom event

I created an api secret and included my measurement_id.

I then tried sending data to GA4 with the example in the article:

  const measurement_id = `G-XXXXXXXXX`;
  const api_secret = `XXXXXXXXXXXXXXXXXXXXXX`;

  await fetch(
    `https://www.google-analytics.com/mp/collect?measurement_id=${measurement_id}&api_secret=${api_secret}`,
    {
      method: "POST",
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        client_id: "123.123333",
        events: [
          {
            name: "conversion",
            params: { succes: true },
          },
        ],
      }),
    }
  );

I cannot get this to work. Does anyone have experience with this or done something similar that can shine some light on what is going wrong here?



Solution 1:[1]

To create a Google Analytics 4 Event tag:

  1. Click Tags > New.
  2. Click Tag Configuration.
  3. Select Google Analytics: GA4 Event.
  4. For Configuration Tag, select the Configuration Tag you created earlier.
  5. For Event Name, specify the name of the event. Use the recommended event names for best results.
  6. Optional: Enter Event Parameters. Use recommended event parameter names for best results.
    1. Click Add Row.
    2. Enter a Parameter Name.
    3. Enter a Value.
  7. Repeat until all desired parameters have been added. Optional: Add any custom user properties that you'd like to configure in User Properties. Note: Analytics automatically logs some user properties. You can set up to 25 additional user properties per Google Analytics 4 property.
  8. Click Triggering and select appropriate events that would cause the tag to fire.
  9. Save the tag configuration and publish your container.
const measurementId = `G-XXXXXXXXXX`;
const apiSecret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
  method: "POST",
  body: JSON.stringify({
    "client_id": "client_id",
    "events": [{
      "name": "generate_lead",
      "params": {
        "currency": "USD",
        "value": 99.99
      }
    }]
  })
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddhartha Mukherjee