javascriptgoogle-analyticsgoogle-tag-manageruniversal-analytics

How to track custom events with GA4 which is set up in Google Tag Manager?


I currently have set up Google Tag Manager on my website via https://developers.google.com/tag-platform/tag-manager/web. So the GTM snippet is in the head of the website.

<!-- 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-XXXXXX');</script>
<!-- End Google Tag Manager -->

Now I want to integrate GA4 into the website but it seems the recommended way to do this is via GTM because you do not need hardcoded G-XXXXXX ids anymore.

So adding the following snippet would be unnecessary right? Taken from https://developers.google.com/analytics/devguides/collection/ga4/events?client_type=gtag

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

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

And sending custom events to GA4 and this is done via

gtag('event', '<event_name>', {
  <event_parameters>
})

But how would I send an event to my G-XXXXX id using GTM? Since I do not have a hardcoded G-XXXXX id anymore, how does GTM know how to link the event to my G-XXXXX id? In the GA4 snippet there is extra code to set up the id after declaring the gtag function but after that is just a datalayer.push.

Is GTM setup enough/the equivalent for the standalone GA4 setup?


Solution

  • It will become a very different way than using gtag to fire the event.

    In GTM

    1. Create a GA4 Configuration Tag enter image description here
    2. Create a GA4 Event Tag. You can choose the configuration tag you just created. enter image description here

    Then set the event name and the parameters you need. Most important you need to set up the right trigger for it. Like when should the event been sent.


    Yes it is equivalent like gtag at the end. Google just use this user-friendly UI and help to send the GA4 request in the GTM.


    add-on for click trigger

    If you want to capture certain button click

    You can use this trigger

    enter image description here

    CSS selector would be the most recommend if you know how to use.

    Otherwise {{Click Class}} or {{Click ID}} would also good to use.