How to use gtag.js instead of analytics.js in a shiny app

Hi. I must use gtag.js instead of analytics.js in my Shiny app, for Google Analytics tracking purpouses. I got to enable tracking (Step 1 in But I don`t know how to enable event tracking (Step 2 in Can I have some tips? Thanks.

1 Like

You don't have to use gtag.js to get tracking its just the latest version of the script, so the older script will still work fine.

However if you want more customisation of the tracking script you can add the javascript directly to the ui.R either via includeScript() or otherwise - some examples from this template are below, which let you install GA, Google Tag Manager or your own:

trackingTags <- function(tag_template = c("ga","gtm","freeform"),

  tag_template <- match.arg(tag_template)

  out <- switch(tag_template,
                ga = sprintf("<script>
                             (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

                             ga('create', '%s', 'auto');
                             ga('send', 'pageview');

                             </script>", tag_code),
                gtm = sprintf("<!-- Google Tag Manager -->
<noscript><iframe src=\"//\"
                height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                <!-- End Google Tag Manager -->", tag_code, tag_code),
                freeform = tag_code



If you are looking to implement event tracking you have a couple of options -

  1. Use Google Tag Manager (that hosts the GA script) you can use its own custom click events to add things like button clicks into GA just using the GTM interface - this is by far the easiest way
  2. You can use the Measurement Protocol to make your own GA hits. This is the most customisable and a proto R library to help is this one - googleMeasureR, but you need to handle things like userIds yourself.
1 Like