Adding web analytics tracking to Streamlit apps

Having gone through all the effort of creating a Streamlit application, you want to know if the people you have shared the application with are actually using it or not.

Luckily, it is straight forward to add web analytics tracking to a Streamlit application.

This post uses a Matomo tracking snippet as an example, but an equivalent process with tracking snippets from other Web Analytics tools such as Google Analytics, Plausible should work fine.

Let’s say we have the following streamlit app,, which contains the following code:

import streamlit as st

st.markdown("# A shiny new Streamlit that is very useful")

And a tracking snippet in the same directory in the file matomo_tracking.html:

<!-- Matomo -->
<script type="text/javascript">
    var _paq = window._paq = window._paq || [];
    /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
    (function() {
      var u="//";
      _paq.push(['setTrackerUrl', u+'matomo.php']);
      _paq.push(['setSiteId', '1']);
      var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
      g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  <!-- End Matomo Code -->

Then we can modify our streamlit application to do the following

  1. Import the html function to allow custom html code in streamlit apps
  2. Read in the contents of the tracking snippet file
  3. Use the html function to embed the html in the streamlit app

The streamlit app will now look like the following:

import streamlit as st
from streamlit.components.v1 import html

st.markdown("# A shiny new Streamlit that is very useful")

with open("matomo_tracking.html") as f:
    html_string =

Now each time the streamlit app is run, this is tracked by Matomo (or your web analytics tool of choice). Of course you can use a tool like Omnibug to double check the data is being sent and what information is contained inside.

Send a Comment

Your email address will not be published.