Ian W
Ian W

Reputation: 990

Tracking with the new Google Analytics 4 (GA4) server-side

Google Analytics 4 (GA4) was recently released and made the default for new properties on the Google Analytics dashboard. I was checking it out and it looks great. We report a lot of our data to Google Analytics via our Node.js server as opposed to client-side using a library called universal-analytics (https://www.npmjs.com/package/universal-analytics), which works very well.

We want to start using GA4 asap but we cannot find any documentation on how to send events to a GA4 property server-side. There are only client-side examples and those don't seem to work at all on a server.

Simply put, what is the serverside equivalent for the following?

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

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

Anyone had success with this?

Upvotes: 14

Views: 10804

Answers (2)

Siddhartha Mukherjee
Siddhartha Mukherjee

Reputation: 2961

It's working perfectly

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": "add_payment_info",
      "params": {
        "currency": "USD",
        "value": 7.77,
        "coupon": "SUMMER_FUN",
        "payment_type": "Credit Card",
        "items": [
          {
            "item_id": "SKU_12345",
            "item_name": "Stan and Friends Tee",
            "affiliation": "Google Merchandise Store",
            "coupon": "SUMMER_FUN",
            "currency": "USD",
            "discount": 2.22,
            "index": 0,
            "item_brand": "Google",
            "item_category": "Apparel",
            "item_list_id": "related_products",
            "item_list_name": "Related Products",
            "item_variant": "green",
            "location_id": "L_12345",
            "price": 9.99,
            "quantity": 1
          }
        ]
      }
    }]
  })
});

Upvotes: 2

Related Questions