How to add Google Analytics to Sveltekit site

How to add Google Analytics to Sveltekit site

Let's see how to add Google Analytics script to a Sveltekit website.

svelte logo

Want a Svelte site built? Hire Me.

Here is how we can add Google Analytics to a Svelte/Sveltekit site.

Create a component called Analytics.svelte inside lib directory.

  export let id = ""

  let analytics = process.env.NODE_ENV !== "development";
  // run analytics only on production

  {#if analytics}
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="{id}"></script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', id);

Now use it in the root layout of the site if you want to track all the pages of the site.


  import Analytics from "$lib/Analytics.svelte"

<Analytics id="G-99XXXXX" />
<!-- everything else -->

Find related articles

Let's discuss on Twitter