Enable Google Analytics 4 (Denali – Mont Blanc)

Prepare your SuiteCommerce Advanced (SCA) implementation of Google Analytics 4 (GA4) without Google Tag Manager (GTM) as described in the following steps. You need to create new folders, files, and modules, so be sure to complete all of the required steps as outlined in the following procedures:

Prepare GoogleAnalytics4@1.0.0 Folders Structure

  1. Go to .../Modules/suitecommerce.

  2. In the suitecommerce folder, create a new folder called GoogleAnalytics4@1.0.0.

  3. In the GoogleAnalytics4@1.0.0 folder, create folders and files using the following structure:

                    Modules/
    └── suitecommerce/
        └── GoogleAnalytics4@1.0.0/
            ├── JavaScript/
            │   └── GoogleAnalytics4.js
            └── ns.package.json 
    
                  

Create GoogleAnalytics4.js File

  1. Go to the JavaScript folder in the structure you created in Prepare GoogleAnalytics4@1.0.0 Folders Structure.

  2. Create the JavaScript file GoogleAnalytics4.js with the following code:

                    // @module GoogleAnalytics4
    /* eslint-disable */
    (function(win, name) {
        // @class GoogleAnalytics4 @extends ApplicationModule
        // ------------------
        // Loads google analytics 4 script and extends application with methods:
        // * trackPageview
        // * trackEvent
        // * trackTransaction
        // Also wraps layout's showInModal
        define('GoogleAnalytics4', [
            'Tracker',
            'underscore',
            'jQuery',
            'Backbone',
            'Utils'
        ], function(Tracker, _, jQuery, Backbone, Utils) {
            var dataLayerName = name + 'DataLayer';
            var GoogleAnalytics4 = {
                // @method doCallback Indicates if this module do a callback after some particular events
                // @return {Boolean}
                doCallback: function() {
                    return !!win[name];
                },
    
                // @method trackPageview
                // @param {String} url
                // @return {GoogleAnalytics4}
                trackPageview: function(url) {
                    if (_.isString(url)) {
                        url = url.split('?')[0];
                        win.gtag('event', 'page_view', { page_location: url, page_title: url });
                    }
    
                    return this;
                },
    
                trackLogin: function(event) {
                    win.gtag('event', 'login', {
                        method: event.category,
                        event_callback: event.callback
                    });
    
                    return this;
                },
    
                trackRegister: function(event) {
                    win.gtag('event', 'sign_up', {
                        method: event.category,
                        event_callback: event.callback
                    });
    
                    return this;
                },
                trackCheckoutAsGuest: function(event) {
                    win.gtag('event', 'checkout_as_guest', {
                        method: event.category,
                        event_callback: event.callback
                    });
    
                    return this;
                },
    
                // @method trackEvent
                // @param {TrackEvent} event
                // @return {GoogleAnalytics}
                trackEvent: function(event) {
                    if (event && event.category && event.action) {
                        win.gtag('event', 'generic_event', {
                            category: event.category,
                            action: event.action,
                            label: event.label,
                            value: parseFloat(event.value) || 0,
                            page: event.page || "/" + Backbone.history.fragment,
                            event_callback: event.callback
                        });
                    }
    
                    return this;
                },
    
                // @method trackTransaction
                // Based on the created SalesOrder we trigger each of the analytics
                // ecommerce methods passing the required information
                // @param {‌LiveOrder.Model} order
                // @return {GoogleAnalytics|Void}
                trackTransaction: function(order) {
                if (order && order.get('confirmation')) {
                   var orderSummary = order.get('summary');
                   var item = null;
    
                   var purchase = {
                      transaction_id: order.get('confirmation').confirmationnumber,
                      value: orderSummary.subtotal,
                      tax: orderSummary.taxtotal,
                      shipping: orderSummary.shippingcost + orderSummary.handlingcost,
                      currency:
                         (SC.ENVIRONMENT.currentCurrency && SC.ENVIRONMENT.currentCurrency.code) ||
                         '',
                      affiliation: GoogleAnalytics4.application.getConfig('siteSettings.displayname'),
                      items: []
                   };
    
                   order.get('lines').each(function (line, index) {
                      item = line.get('item');
    
                      purchase.items.push({
                         item_id: item.get('_sku'),
                         item_name: item.get('_name'),
                         affiliation: GoogleAnalytics4.application.getConfig('siteSettings.displayname'),
                         currency:
                            (SC.ENVIRONMENT.currentCurrency &&
                               SC.ENVIRONMENT.currentCurrency.code) ||
                            '',
                         index: index,
                         item_category: item.get('_category') || '',
                         item_variant: '',
                         price: line.get('rate'),
                         quantity: line.get('quantity')
                      });
                   });
    
                   win.gtag('event', 'purchase', purchase);
    
                }
    
                return this;
                },
    
                // @method addCrossDomainParameters
                // @param {string} url
                // @return {String} url
                addCrossDomainParameters: function(url) {
                    // We only need to add the parameters if the URL we are trying to go
                    // is not a sub domain of the tracking domain
                    if (_.isString(url)) {
                        url = Utils.addParamsToUrl(url, {
                            client_id: win[name].client_id,
                            session_id: win[name].session_id
                        });
                    }
    
                    return url;
                },
    
                // @method loadScript
                // @return {jQuery.Promise|Void}
                loadScript: function(id) {
                    return jQuery.getScript(
                        '//www.googletagmanager.com/gtag/js?id=' + id + '&l=' + dataLayerName
                    );
                },
    
                // @method mountToApp
                // @param {ApplicationSkeleton} application
                // @return {Void}
                mountToApp: function(application) {
                    GoogleAnalytics4.application = application;
                    var tracking = GoogleAnalytics4.application.getConfig('tracking.googleAnalyticsFour');
    
                    // if track page view needs to be tracked
                    if (tracking && tracking.propertyID && !SC.isPageGenerator()) {
                        win[dataLayerName] = win[dataLayerName] || [];
                        win.gtag =
                            win.gtag ||
                            function() {
                                win[dataLayerName].push(arguments);
                            };
                        var domains = [];
                        if (tracking.domainName) {
                            domains.push(tracking.domainName);
                        }
                        if (tracking.domainNameSecure) {
                            domains.push(tracking.domainNameSecure);
                        }
    
                        if (domains.length) {
                            win.gtag('set', 'linker', {
                                domains: domains
                            });
                        }
    
                        var configOptions = {
                            send_page_view: false
                        };
    
                        var client_id = Utils.getParameterByName(win.location.href, 'client_id');
                        var session_id = Utils.getParameterByName(win.location.href, 'session_id');
    
                        if (client_id && session_id) {
                            configOptions.client_id = client_id;
                            configOptions.session_id = session_id;
                        }
    
                        win.gtag('js', new Date());
                        win.gtag('config', tracking.propertyID, configOptions);
    
                        // Please keep this statement here or the first pageView on site load
                        // will not be triggered (ApplicationSkeleton.Layout._showContent)
                        Tracker.getInstance().trackers.push(GoogleAnalytics4);
    
                        // the analytics script is only loaded if we are on a browser
                        application.getLayout().once('afterAppendView', function() {
                            GoogleAnalytics4.loadScript(tracking.propertyID)
                                .done(function() {
                                    win[name] = {};
                                    win.gtag('get', tracking.propertyID, 'client_id', function(client_id) {
                                        win[name].client_id = client_id;
                                    });
                                    win.gtag('get', tracking.propertyID, 'session_id', function(session_id) {
                                        win[name].session_id = session_id;
                                    });
                                })
                                .fail(function(jqXhr) {
                                    jqXhr.preventDefault = true;
                                    console.warn('Google Analytics 4 was unable to load');
                                });
                        });
                    }
                }
            };
    
            return GoogleAnalytics4;
        });
    })(window, 'ga4'); 
    
                  

Create ns.package.json File

  1. Go to the GoogleAnalytics4 folder in the structure you created in Prepare GoogleAnalytics4@1.0.0 Folders Structure.

  2. Create and save the json file, ns.package.json, with the following code:

                    {
        "gulp": {
            "javascript": ["JavaScript/*.js"]
        }
    } 
    
                  
  3. Save your changes.

Add entryPoints Module to Application Dependencies

  1. Open the distro.json file in the root SCA development directory and add GoogleAnalytics4 to the dependencies attribute in the entryPoints for the Shopping, Checkout, and MyAccount applications.

    The following sample shows what your updated code will look like:

                    {
       ...
        "tasksConfig": {
          ...
            "javascript": {
                "entryPoints": [
                    {
                        "names": ["SC.Shopping.Starter"],
                        "exportFile": "shopping.js",
                        "dependencies": [
                            "GoogleAnalytics4",
                            ...
                        ]
                    },
                    {
                        "names": ["SC.MyAccount.Starter"],
                        "exportFile": "myaccount.js",
                        "dependencies": [
                            "GoogleAnalytics4",
                            ...
                        ]
                    },
                    {
                        "names": ["SC.Checkout.Starter"],
                        "exportFile": "checkout.js",
                        "dependencies": [
                            "GoogleAnalytics4",
                            ...
                        ]
                    }
             ]
             ...
          ...
       ...
    } 
    
                  
  2. Save the distro.json file.

Add googleAnalyticsFour to Tracking Property

  1. Go to .../Modules/suitecommerce/ShoppingApplication@X.X.X/JavaScript/ and open the JavaScript file, SC.Shopping.Configuration.js.

  2. In the Configuration object, inside the tracking property, add the googleAnalyticsFour property.

    The following sample shows what your updated code will look like:

                    var Configuration = {
        ...
                    ,               tracking: {
                        ...
                                    ,               googleAnalyticsFour: {
                                                    // Enter the Google Analytics 4 Tracking ID. SuiteCommerce Advanced inserts this property into each page of the application.
                                                    // To locate the tracking ID, login to your Google Analytics 4 account and go to Admin > Data Streams > select your data stream > MEASUREMENT ID.
                                                    // Format: G-XXXXXXXXXX
                                                    propertyID: '',
                                                    // Enter the domain used for Google Analytics. The value you enter depends on which application you want to use Google Analytics
                                                    domainName: '',
                                                    // Enter the secure domain used for Google Analytics 4. Possible values are the same as the Google Analytics Domain property.
                                                    domainNameSecure: ''
                                    }
                    }
    }; 
    
                  
  3. Save the SC.Shopping.Configuration.js file.

  4. Go to .../Modules/suitecommerce/CheckoutApplication@X.X.X /JavaScript/ and open the JavaScript file, SC.Checkout.Configuration.js.

  5. In the Configuration object, inside the tracking property, add the googleAnalyticsFour property.

    The following sample shows what your updated code will look like:

                    var Configuration = {
        ...
                    ,               tracking: {
                        ...
                                    ,               googleAnalyticsFour: {
                                                    // Enter the Google Analytics 4 Tracking ID. SuiteCommerce Advanced inserts this property into each page of the application.
                                                    // To locate the tracking ID, login to your Google Analytics 4 account and go to Admin > Data Streams > select your data stream > MEASUREMENT ID.
                                                    // Format: G-XXXXXXXXXX
                                                    propertyID: '',
                                                    // Enter the domain used for Google Analytics. The value you enter depends on which application you want to use Google Analytics
                                                    domainName: '',
                                                    // Enter the secure domain used for Google Analytics 4. Possible values are the same as the Google Analytics Domain property.
                                                    domainNameSecure: ''
                                    }
                    }
    }; 
    
                  
  6. Save the SC.Checkout.Configuration.js file.

  7. Go to .../Modules/suitecommerce/MyAccountApplication.SCA@X.X.X /JavaScript/ and open the JavaScript file, SC.MyAccount.Configuration.js.

  8. In the Configuration object, inside the tracking property, add the googleAnalyticsFour property.

    The following sample shows what your updated code will look like:

                    var Configuration = {
        ...
                    ,               tracking: {
                        ...
                                    ,               googleAnalyticsFour: {
                                                    // Enter the Google Analytics 4 Tracking ID. SuiteCommerce Advanced inserts this property into each page of the application.
                                                    // To locate the tracking ID, login to your Google Analytics 4 account and go to Admin > Data Streams > select your data stream > MEASUREMENT ID.
                                                    // Format: G-XXXXXXXXXX
                                                    propertyID: '',
                                                    // Enter the domain used for Google Analytics. The value you enter depends on which application you want to use Google Analytics
                                                    domainName: '',
                                                    // Enter the secure domain used for Google Analytics 4. Possible values are the same as the Google Analytics Domain property.
                                                    domainNameSecure: ''
                                    }
                    }
    }; 
    
                  
  9. Save the SC.MyAccount.Configuration.js file.

Test and Deploy Your Customizations

Follow the instructions provided in Test SCA Customizations on a Local Server and Deploy SCA Customizations to NetSuite to test and deploy your customizations.

Related Topics

Guide to Enable Google Analytics 4
Enable Google Analytics 4 (SCA 2019.2 – 2022.1)
Enable Google Analytics 4 (SCA Vinson – 2019.1)

General Notices