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 -->