SvelteKit google analytics double reporting

Viewed 448

I'm looking for the right way to set up google analytics in my sveltekit application.

app.html

<script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING_ID"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
            window.dataLayer.push(arguments);
    }
    gtag('js', new Date());
    gtag('config', 'TRACKING_ID');
</script>

__layout.svelte

$: {
        console.log('page: ' + $page.url.pathname);
        if (typeof gtag !== 'undefined') {
            console.log('callign gtag: ' + $page.url.pathname);
            gtag('config', trackingId, {
                page_path: $page.url.pathname
            });
        }
    }

It works fine the only problem is a double reporting

I can see a page twice instead of once :(

Can help me, please?

3 Answers

I use this script. I found it from a Youtuber but I don't remember the channel to reference.

I import it to __layout.svelte. This helps to initiate the gtag on Production and reference visited pages correctly.

<script>

import { page } from '$app/stores';


    $: if (typeof gtag !== 'undefined' && import.meta.env.PROD == true) {
        if ($page.query.toString().length > 0) {
            gtag('config', 'GA_MEASUREMENT_ID', {
                page_path : $page.path,
                page_location: `${$page.host}${$page.path}?${$page.query}`,
            });
        } else {
            gtag('config', 'GA_MEASUREMENT_ID', {
                page_path : $page.path,
                page_location: `${$page.host}${$page.path}`,
            });
        }
    }


</script>

I worked it out with a component I import in __layout

<script lang="ts">
    import { GA_MEASUREMENT_ID } from '$lib/environment';
    export let id = GA_MEASUREMENT_ID;
    if (typeof window !== 'undefined') {
        window.dataLayer = window.dataLayer || [];
        window.gtag = function gtag(): void {
            window.dataLayer.push(arguments);
        };
        window.gtag('js', new Date());
        window.gtag('config', id);
    }
</script>

<svelte:head>
    <script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script>
</svelte:head>

I've been having the same problem, I followed a youtube tutorial to set it up but I'm pretty sure you don't need the reactive statement..

If you go to your stream in google analytics and find the measuring settings panel and under page views, click to show advanced settings, you should see that by default it tracks page changes based on the browser page history - which the sveltekit SPA router does by default.. so just getting rid of the reactive statement worked for me

enter image description here

Related