How to add Google Analytics to Sveltekit site

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

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

Create a component called Analytics.svelte inside lib directory.

<script>
  export let id = ""

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

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

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

+layout.svelte

<script>
  import Analytics from "$lib/Analytics.svelte"
</script>

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

Find related articles

Let's discuss on Twitter