# Google Analytics component

**URL:** <https://discuss.streamlit.io/t/google-analytics-component/13878>\
**Category:** Custom Components\
**Created:** [June 11, 2021, 4:13am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878 "2021-06-11T04:13:32Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bobby](https://avatars.discourse-cdn.com/v4/letter/b/df788c/32.png) [@Bobby](https://discuss.streamlit.io/u/Bobby)\
**Post date:** [June 11, 2021, 4:13am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/1 "2021-06-11T04:13:32Z")

</div>

I am trying to make a simple component to enable google analytics, and I can’t seem to get it to work.

```auto
import streamlit.components.v1 as components

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

        gtag('config', google_analytics_id);
        </script>
	""",
        height=1,
        scrolling=False,
    )

```

Then in my app.py sidebar menu page, I have call the component. But I do not see the script loaded.

---

<div class="post-metadata">

**Author:** ![Rushmore](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/rushmore/32/29472_2.png) [@Rushmore](https://discuss.streamlit.io/u/Rushmore)\
**Post date:** [June 12, 2021, 6:04am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/2 "2021-06-12T06:04:00Z")

</div>

Try [statcounter](https://statcounter.com), simpler to use and works. Same implementation as the above, but it works. Also, [this](https://github.com/jrieke/streamlit-analytics) seems relatively straight forward. I wouldn’t waste any further time on google analytics. But if you can get it to work like [he](https://discuss.streamlit.io/t/how-to-add-google-analytics-or-js-code-in-a-streamlit-app/1610/11) did, then be my guest.

---

<div class="post-metadata">

**Author:** ![Bobby](https://avatars.discourse-cdn.com/v4/letter/b/df788c/32.png) [@Bobby](https://discuss.streamlit.io/u/Bobby)\
**Post date:** [June 12, 2021, 6:15am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/3 "2021-06-12T06:15:10Z")

</div>

I really want to use Google Analytics as I am interested in much more than just how many hits. I want to know geo location, sources, and other things.

---

<div class="post-metadata">

**Author:** ![Rushmore](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/rushmore/32/29472_2.png) [@Rushmore](https://discuss.streamlit.io/u/Rushmore)\
**Post date:** [June 12, 2021, 9:23am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/4 "2021-06-12T09:23:13Z")

</div>

Yeah, statcounter gives you all that too. Their location, IP address, country, and more data.

 ![kkk](https://global.discourse-cdn.com/streamlit/original/2X/5/58ca2aa653ad398390b66d498a86675d3e2a411a.png)

---

<div class="post-metadata">

**Author:** ![Bobby](https://avatars.discourse-cdn.com/v4/letter/b/df788c/32.png) [@Bobby](https://discuss.streamlit.io/u/Bobby)\
**Post date:** [June 12, 2021, 2:51pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/5 "2021-06-12T14:51:29Z")

</div>

I still prefer to use Google Analytics for a few reasons, but I also want to know why it doesn’t work for future components. The link you posted to the one that got it working didn’t work. I did read a few convoluted ways to get it working, but I wanted to use a component as it feels like the right way to do it.

---

<div class="post-metadata">

**Author:** ![Rushmore](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/rushmore/32/29472_2.png) [@Rushmore](https://discuss.streamlit.io/u/Rushmore)\
**Post date:** [June 12, 2021, 6:40pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/6 "2021-06-12T18:40:40Z")

</div>

Understood, all the best with it 🙂

---

<div class="post-metadata">

**Author:** ![Emmanuel\_Pean](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/emmanuel_pean/32/48875_2.png) [@Emmanuel\_Pean](https://discuss.streamlit.io/u/Emmanuel_Pean)\
**Post date:** [November 3, 2021, 4:26pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/7 "2021-11-03T16:26:21Z")

</div>

Just reopening this thread to ask how do you install statcounter.  
I’ve created an account and added the following in my main script.

```auto
components.html("""<!-- Default Statcounter code for Pears
https://pearstest.herokuapp.com -->
<script type="text/javascript">
var sc_project=12673269; 
var sc_invisible=1; 
var sc_security="1c2a1959"; 
</script>
<script type="text/javascript"
src="https://www.statcounter.com/counter/counter.js"
async></script>
<noscript><div class="statcounter"><a title="Web Analytics"
href="https://statcounter.com/" target="_blank"><img
class="statcounter"
src="https://c.statcounter.com/12673269/0/1c2a1959/1/"
alt="Web Analytics"
referrerPolicy="no-referrer-when-downgrade"></a></div></noscript>
<!-- End of Statcounter Code -->""")

```

However, startcounter cannot detect the code on my website.  
Any help would be very appreciated 🙂

Emmanuel

---

<div class="post-metadata">

**Author:** ![jp-varela](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/jp-varela/32/3003_2.png) [@jp-varela](https://discuss.streamlit.io/u/jp-varela)\
**Post date:** [November 12, 2021, 4:40pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/8 "2021-11-12T16:40:46Z")

</div>

Just want to update this if anyone need it. Another alternative to track your Streamlit visits:

> **[Streamlit Analytics](https://medium.com/@joao.varela/streamlit-analytics-20aef7f41b6b)**
>
> If you are a Streamlit developer and want a free easy way to monitor your app visits and find insights about your customer's behavior, this…

---

<div class="post-metadata">

**Author:** ![Hanan\_Shteingart](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/hanan_shteingart/32/13169_2.png) [@Hanan\_Shteingart](https://discuss.streamlit.io/u/Hanan_Shteingart)\
**Post date:** [February 6, 2022, 1:26pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/9 "2022-02-06T13:26:49Z")

</div>

an ugly hack:

```auto
def inject_ga():
    """Add this in your streamlit app.py
    see https://github.com/streamlit/streamlit/issues/969
    """
    # new tag method
    GA_ID = "google_analytics"
    # NOTE: you should add id="google_analytics" value in the GA script
    # https://developers.google.com/analytics/devguides/collection/analyticsjs
    GA_JS = """
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX"> id="google_analytics" </script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXXXXX');
</script>
"""
    # Insert the script in the head tag of the static template inside your virtual
    index_path = pathlib.Path(st. __file__ ).parent / "static" / "index.html"
    logging.info(f'editing {index_path}')
    soup = BeautifulSoup(index_path.read_text(), features="lxml")
    if not soup.find(id=GA_ID): # if cannot find tag
        bck_index = index_path.with_suffix('.bck')
        if bck_index.exists():
            shutil.copy(bck_index, index_path) # recover from backup
        else:
            shutil.copy(index_path, bck_index) # keep a backup
        html = str(soup)
        new_html = html.replace('<head>', '<head>\n' + GA_JS)
        index_path.write_text(new_html)

```

---

<div class="post-metadata">

**Author:** ![need\_help](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/need_help/32/24394_2.png) [@need\_help](https://discuss.streamlit.io/u/need_help)\
**Post date:** [March 22, 2023, 4:34am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/10 "2023-03-22T04:34:16Z")

</div>

Thanks. I just implemented the statcounter and super straight forward, stats is available right way.

Question:

What if I have a multiple page streamlit application, do I need to add the statcounter code on everypage? Is there any smart way of doing it?

---

<div class="post-metadata">

**Author:** ![ameliacohen](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/ameliacohen/32/31840_2.png) [@ameliacohen](https://discuss.streamlit.io/u/ameliacohen)\
**Post date:** [September 7, 2023, 5:19pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/11 "2023-09-07T17:19:38Z")

</div>

How did you get statcounter to work on your site? I can see the code but statcounter is saying they are unable to access my site.

---

<div class="post-metadata">

**Author:** ![GabrielMenezes](https://avatars.discourse-cdn.com/v4/letter/g/ea666f/32.png) [@GabrielMenezes](https://discuss.streamlit.io/u/GabrielMenezes)\
**Post date:** [January 21, 2024, 7:26pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/12 "2024-01-21T19:26:33Z")

</div>

There is a basic example of how to implemente Google Analytics in Streamlit via bi-directional components API. A lot of things to improve, but it works.

> **[GitHub - dmenezesgabriel/streamlit-gtag](https://github.com/dmenezesgabriel/streamlit-gtag)**
>
> Contribute to dmenezesgabriel/streamlit-gtag development by creating an account on GitHub.

---

<div class="post-metadata">

**Author:** ![Amit8](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/amit8/32/53730_2.png) [@Amit8](https://discuss.streamlit.io/u/Amit8)\
**Post date:** [February 9, 2025, 2:26am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/13 "2025-02-09T02:26:09Z")

</div>

How can we install this plugin ? couldnt find it in pip

---

<div class="post-metadata">

**Author:** ![Amit8](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/amit8/32/53730_2.png) [@Amit8](https://discuss.streamlit.io/u/Amit8)\
**Post date:** [February 10, 2025, 6:57am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/14 "2025-02-10T06:57:01Z")

</div>

How can we install this plugin ? couldnt find it in pip

---

<div class="post-metadata">

**Author:** ![Marcelo17](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/marcelo17/32/65785_2.png) [@Marcelo17](https://discuss.streamlit.io/u/Marcelo17)\
**Post date:** [June 25, 2025, 9:11pm UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/15 "2025-06-25T21:11:57Z")

</div>

I just documented a solution here: [GitHub - MarceloCajueiro/streamlit-html-injection-docker: Elegant solution for injecting HTML tags (Google Tag Manager, Analytics, SEO meta tags) into Dockerized Streamlit applications. Uses build-time SED injection for reliable, production-ready HTML customization without runtime overhead.](https://github.com/MarceloCajueiro/streamlit-html-injection-docker)

---

<div class="post-metadata">

**Author:** ![vox](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/vox/32/66051_2.png) [@vox](https://discuss.streamlit.io/u/vox)\
**Post date:** [July 4, 2025, 8:55am UTC](https://discuss.streamlit.io/t/google-analytics-component/13878/16 "2025-07-04T08:55:56Z")

</div>

This is what i do to inject my gtag:

```auto
Post-install script to inject Google Analytics into Streamlit
This script runs after pip install to modify the Streamlit static files
"""
import os
import sys
import streamlit as st

def inject_google_analytics():
    """Inject Google Analytics into Streamlit's index.html"""
    
    # Get Streamlit installation directory
    streamlit_dir = os.path.dirname(st. __file__ )
    index_file = os.path.join(streamlit_dir, 'static', 'index.html')
    
    print(f"Streamlit directory: {streamlit_dir}")
    print(f"Index file: {index_file}")
    
    if not os.path.exists(index_file):
        print(f"Error: Streamlit index.html not found at {index_file}")
        return False
    
    # Read the current file
    with open(index_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Check if Google Analytics is already injected
    if 'gtag' in content:
        print("Google Analytics already injected")
        return True
    
    # Google Analytics code to inject
    ga_code = ''' <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-(yourtag)"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'G-(your tag)');
    </script>
    
'''
    
    # Inject after <head> tag
    modified_content = content.replace('<head>', f'<head>\n{ga_code}')
    
    # Write back to file
    with open(index_file, 'w', encoding='utf-8') as f:
        f.write(modified_content)
    
    print("Google Analytics injected successfully!")
    return True

if __name__ == " __main__":
    print("Injecting Google Analytics into Streamlit...")
    success = inject_google_analytics()
    sys.exit(0 if success else 1)

```

Now just run “python inject\_analytics.py” after the packages are installed. Although, this is not a good practice, it’s the only way it works.
