gtag.js implementation
Tag Management

Gtag.js Implementation Guide for GA4 Tracking

Each tagging tool has its pros and cons. While Google Tag Manager is the ideal tag management solution for most of the companies, in some specific cases, different methods are required for some companies. In this article, I will consider different aspects of Global site tag or Google Tag (gtag.js) and how you can implement it for GA4 tracking.

Table of Contents

    What is Global Site Tag or Google Tag (gtag.js)

    Google Tag or Global Site Tag (gtag.js) is essentially a JavaScript library that allows you to send hits to Google products. As a marketer, you are likely familiar with the fact that we primarily use Google Tag Manager (GTM) to dispatch hits to marketing platforms or third-party vendors. However, it’s important to note that GTM is not the sole option. If your goal is to exclusively transmit hits to Google products, you also have the alternative of utilizing gtag.js.

    What are the Differences Between gtag.js and Google Tag Manager (GTM)

    Both of these are tag management solutions. Google Tag Manager is an enhanced and visualized version of gtag.js. While you can also utilize Google Tag Manager to transmit information to Google products, it offers additional capabilities such as:

    • Send hits to 3rd party platforms like Facebook, Linkedin, Snapchat, Tiktok, Criteo, Pinterest, all Google products etc.
    • Adding custom JavaScript or HTML codes to the website
    • Pre-defined triggers and variables that you can easily for your tags
    • Non-technical friendly and easy to implement
    • Version control solutions
    • Visual user interface

    In contrast to Google Tag Manager, gtag.js is more limited in its functionalities.

    • It is more suitable for technical developers due to its technical nature
    • Send data only Google products like Adwords, DV360, Floodlight, Google Analytics etc.
    • Tehnical and developer friendly
    • No visual interface
    • More flexibility

    Taking all these factors into account, we can conclude that gtag.js is more result-oriented for sending data to Google products, whereas Google Tag Manager stands out as an enhanced visual tag management platform.

    Why You Should Use gtag.js

    Personally, I recommend using Google Tag Manager for tag management. As I explained earlier, it offers additional capabilities that you can readily employ by adding a single code to your website. However, here are some reasons to consider using gtag.js:

    • If your objective is sending data exclusively to Google products,
    • To prevent the addition of unnecessary extra codes to your page
    • By eliminating unused variables and triggers, thus improving site speed
    • Opting for a quicker solution to commence sending events to Google products, rather than embarking on learning the Google Tag Manager platform from scratch.

    Configuration and Page Views

    To begin, you need to incorporate the gtag.js library into your website, just as you would for Google Tag Manager. For instance, if your intention is to initiate event transmission to GA4, follow these steps on the Google Analytics 4 panel:

    • Go to “Admin”
    • Select “Data Streams”
    • Choose your specific data stream
    • Click on “View tag instructions”
    • Opt for the “Install manually” option
    • Within this section, you will find the gtag library codes that are tailored for your property. Here’s an example for reference:
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'G-XXXXXXXXXX');
    </script>

    After successfully integrating the gtag.js into your website, it will immediately start to sending page views to your GA4 property. If you prefer not to transmit page views automatically, you have the option to utilize the “send_page_view: false” command. This can be achieved by passing an object to the gtag config line.

    gtag('config', 'G-XXXXXXXXXX',{
      send_page_view : false
    });

    You will probably want to test or debug your implementation. To activate it pass debug_mode:1 parameter to the config object. Then you can see all the events that you send under “Debug View” page on GA4.

    Please note that if you intend to transmit data to multiple Google products, you need to include a configuration line for each respective product, as illustrated below:

    gtag('config', 'G-XXXXXXXXXX'); // Google Analytics 4 properties
    gtag('config', 'AW-XXXXXXXXXX'); // AdWords
    gtag('config', 'DC-XXXXXXXXXX'); // Ads 360

    Gtag.js for Single Page Applications (SPA)

    There are two options for handling page views:

    Option 1: For single-page applications, it’s acceptable to include the entire gtag code without a config line. As I previously explained, the config line automatically sends page views to GA4. Alternatively, you can choose to execute the “config” line with each router change. This approach enables you to transmit page views when users switch pages. Another possibility is to retain the config line during the initial page load and subsequently dispatch the page view event separately on the second page view or router change, using the following code:

    gtag('event', 'page_view');

    I advise passing page-related information to the config command or the page view event, considering that virtual changes to the DOM, URL, title, etc. can potentially create timing issues. Here’s an example to illustrate this point:

    gtag('config', 'G-XXXXXXXXXX',{
      page_location : "https://sertacartun.com/home"
      page_path : "/home"
      page_title : "Home page"
    });

    Important Note: On single-page applications (SPAs), it’s crucial to populate the page location information with the URL of the “first” page until the user leave the website. This approach is necessary to address the issue of rogue referrals. For additional information, please refer to here.

    Option 2: Alternatively, you can effortlessly employ the “Enhanced Measurement” option available within the GA4 data streams panel. This feature enables you to capture page changes triggered by history state modifications. However, please note that it might pose challenges when attempting to transmit additional parameters along with page views.

    User Properties

    User properties enable you to enhance user identification and categorization by assigning distinct values. For instance, if you aim to categorize your app users, you can assign the value ‘app_user:true’ as a user property. The only requirement is to establish user properties using the gtag command before to the config setup.

    gtag('set', 'user_properties', {
      app_user:'true'
    });
    
    gtag('config','G-XXXXXXXXX')

    Please be aware that when transmitting data to multiple Google products simultaneously, it’s essential to configure user properties for a singular stream to exclusively target GA4. The following logic can be placed for this purpose:

    gtag('config', 'G-XXXXXXXXX', {
      'user_properties': {
         app_user:'true'
      }
    })

    Send Custom Events and Event Parameters

    If your intention is to dispatch custom events to Google Analytics 4, you need to execute the following command:

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

    The variable event_name should dynamically represent the user action, reflecting its specific nature. Furthermore, the event_parameters should encapsulate comprehensive information pertinent to the tracked action. As an example, imagine you wish to monitor menu clicks. In such a scenario, the event_name variable could be “menu_click,” and you can enhance this event with supplementary data through the event_parameters, as demonstrated below:

    menu_name: ‘phones’,
    menu_url: ‘https://yoursite.com/phones’


    For custom events, you have complete freedom over the parameters and event names. However, it’s vital to ensure that you should also create the event parameters with identical names in GA4. Otherwise, these parameters won’t be usable in your reports.

    Additionally, the non_interaction value defaults to false. To avoid any potential issues with bounce rates, I recommend setting a true/false value for each event.

    An exceptionally crucial topic to note is that when you dispatch a page view or event using gtag.js, it naturally sends hits to all initialized Google products. To prevent this, the send_to parameter should be placed. Here’s an example:

    gtag('event', 'menu_click', {
      menu_name : 'phones',
      menu_url : 'https://yoursite.com/phones',
      send_to : 'G-XXXXXXXXXX'
    });

    Measure Enhanced Ecommerce

    Unlike the Universal Analytics, GA4 introduces pre-defined event names for ecommerce actions. Therefore, when transmitting Ecommerce actions, it’s important to use these pre-defined names. Below, I will present a comprehensive list of these event names, along with explanations and the allowed parameters:

    Event NameExplanationAllowed Parameters
    view_item_listUser sees a product listing area like category pages, search results, recommendations etc.– item_list_id
    – item_list_name
    – items
    select_itemUser clicks the product that we show on listing pages – item_list_id
    – item_list_name
    – items
    view_itemUser lands on the product page– currency
    – value
    – items
    add_to_cartUser adds a product to the cart– currency
    – value
    – items
    add_to_wishlistUser adds a product to the wishlist– currency
    – value
    – items
    view_cartUser navigate to the cart page– currency
    – value
    – items
    remove_from_cartUser removes a product to the wishlist– currency
    – value
    – items
    begin_checkoutUsers navigates to the first step of checkout process– currency
    – coupon
    – value
    – items
    checkout_progressUsers navigates to other steps before purchase– checkout_step
    – currency
    – coupon
    – value
    – items
    add_shipping_infoUsers adds / selects shipping info– currency
    – coupon
    – value
    – shipping_tier
    – items
    add_payment_infoUsers adds / selects payment info– currency
    – coupon
    – value
    – payment_type
    – items
    purchaseUser makes a transaction– transaction_id
    – value
    – tax
    – shipping
    – currency
    – coupon
    – items
    refundUser makes a refund– transaction_id
    – value
    – tax
    – shipping
    – currency
    – coupon
    – items
    view_promotionUser views a promotion item or banner– creative_name
    – creative_slot
    – promotion_name
    – promotion_id
    – items
    select_promotionUser clicks a promotion item or banner– creative_name
    – creative_slot
    – promotion_name
    – promotion_id
    – items
    For detailed information you can visit the gtag enhanced ecommerce documentation and events reference pages.

    Items Object

    As evident from the above, all ecommerce events requires an “items” object. This signifies that you need to provide item details for each enhanced ecommerce event to facilitate accurate reporting. Here are the essential parameters for the “items” object:

    ParameterExplanationRelated Event Item Object
    item_idID/SKU of the product (string)All
    item_nameName of the product (string)All
    affiliationA product affiliation to designate a supplying company (string)All
    couponItem level coupon code if coupon applied for a spesific item (string)begin_checkout, checkout_progress, add_shippig_info, add_payment_info, purchase, refund
    discountDiscount amount for the product (float/integer)All
    indexPosition of the product on a listing area (integer)view_item_list, select_item_list
    item_brandBrand of the product (string)All
    item_categoryMain category of the product (string)All
    item_category2Level 2 sub category of the product (string)All
    item_category3Level 3 sub category of the product (string)All
    item_category4Level 4 sub category of the product (string)All
    item_category5Level 5 sub category of the product (string)All
    item_list_idID of the item list that user interacted with the product (string)view_item_list, select_item_list
    item_list_nameName of the item list that user interacted with the product (string)view_item_list, select_item_list
    item_variantVariant of the item (string)All
    location_idID of the products pyshical store (string)All
    pricePrice of the product (integer/float)All
    quantityQuantity of the productadd_to_cart, remove_from_cart,view_cart, begin_checkout, checkout_progress, purchase
    Please see event reference page for more information

    Example Ecommerce Event

    Lastly, I’d like to provide a complete example of an ecommerce purchase event. This will give you a clear idea of all the variables and the corresponding values that need to be included. If you utilize the code below and modify the values to match the actual order details once the payment process is finished, you’ll successfully transmit a purchase event to your Google Analytics 4 property.

    gtag("event", "purchase", {
      transaction_id: "T_12345_3", // Order ID - Should be unique for each order.
      value: 25.42, // Total order amount that used paid - should be float or integer
      tax: 4.90, // Total tax amount in the order
      shipping: 5.99, // Total shipping amount
      currency: "USD", //ISO currency code for order
      coupon: "SUMMER_SALE", // Voucher-Coupon code that applied to whole order
      items: [{
         item_id: "SKU_12345", // item id
         item_name: "Stan and Friends Tee", // item name
         affiliation: "Google Merchandise Store", // afilliaton
         coupon: "SUMMER_FUN", // item level coupon if there is one
         discount: 2.22, // total discount applied to the product
         item_brand: "Google", // Brand of the product
         item_category: "Apparel", // category level 1
         item_category2: "Adult", // category level 2
         item_category3: "Shirts", // category level 3
         item_category4: "Crew", // category level 4
         item_category5: "Short sleeve", // category level 5
         item_variant: "green", // variant if has more than one
         location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo", //store id where product is physically located
         price: 9.99, // price of the product that user paid
         quantity: 1 // total quantity that user bought
      }]
    });
    
    Note : If you set your main currency as USD on GA4, it will automatically convert the amount to USD when you send any other curency information with purchase event.

    Conclusion

    I tried my best to explain the entire gtag.js implementation process for GA4. Remember that Google Tag Manager isn’t the only tool for digital analytics. It’s essential to diversify your technical skills. Hopefully, the article has been helpful to you. If you have any questions or issues, please don’t hesitate to leave a comment. Cheers!

    Leave a Reply

    Your email address will not be published. Required fields are marked *