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=""></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-xxxxxxxx-x');

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:


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 ( and more advanced usage, such as tracking individual events on the page (

See Also

comments powered by Disqus