Tracking application analytics with google analytics

Hey everyone!

I’m looking for a way to track how many people are accessing my dash app and and added bonus would be to have their country as well. Any thoughts on how I could implement this? Google analytics would be a great tool but I am unsure on how to implement it.\

Thanks for the help,

Morgan

1 Like

This worked for me

app = dash.Dash(...)

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

            gtag('config', 'UA-999999-1', { 'anonymize_ip': true });
        </script>
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>"""

You will need your own UA number instead of 999999-1.

This particular setup includes anonymization of IP addresses.

3 Likes

This didn’t work for me. I get an syntax error when I write html code in app.py

app = dash.Dash(....) 

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

            gtag('config', 'G-XXXXXXXX');
        </script>
    </head>
</html>
<html>
    ^
SyntaxError: invalid syntax

Do you assign it to app.index_string?

Aha, I didn’t. Just saw the docs: Adding CSS & JS and Overriding the Page-Load Template | Dash for Python Documentation | Plotly