DEV Community

Cover image for Google Analytics Tag using Astro
Tona
Tona

Posted on

Google Analytics Tag using Astro

If you are using Astro and want to add Google Analytics with the copy/paste version provided by Google itself, which is the following.

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

      gtag("config", "G-V");
    </script>
Enter fullscreen mode Exit fullscreen mode

Just note that Astro by default would convert the second script tag without any attributes to a module type meaning that the function gtag would be scoped to that single script tag.

The fix is super simple, just remember to add type="application/javascript" so that Astro doesn't infer the script tag to a module one.

<!-- first script tag -->
<script type="application/javascript">
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Follow me on Twitter, @tonadev

Photo by Joao Tzanno on Unsplash

Top comments (0)