How to add Google Analytics to a Shiny application

I recently wanted to add a Google Analytics tracker to a Shiny dashboard, and I found that the official documentation doesn’t explain how to include “Global Site Tag” tracking code, which seems to be the current default setting in Analytics. The process is simple, we just have to include the tracking code as an HTML snippet in ui.R. The process requires only two steps:

  1. Copy the analytics HTML snippet into a text file
  2. Reference the file in ui.R

1. Find and copy the tracker snippet

You’ll find this snippet on your Analytics console, in Admin > Tracking Info > Tracking Code. You may need to create a Property first, from the drop-down menu of the Property column in the Admin console.

I created a file named google-analytics.html, in the same directory as ui.R, and copied into it the HTML snippet, which looks like this:

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

  gtag('config', 'UA-xxxxxxxx-x');
</script>

The x’s should of course be replaced by your own id.

2. Reference the file in ui.R

Next, include the file in ui.R, towards the top of your fluidPage:

shinyUI(fluidPage(
  tags$head(includeHTML(("google-analytics.html"))),
  ...

That’s all! Your published app will now send visitor statistics to Google Analytics.

Further reading

The official Shiny docs are still relevant for more information on creating Properties (https://shiny.rstudio.com/articles/google-analytics.html) and more advanced usage, such as tracking individual events on the page (https://shiny.rstudio.com/articles/usage-metrics.html).

See Also

comments powered by Disqus