Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SvelteKit google analytics double reporting

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?

like image 838
user3887366 Avatar asked Sep 16 '26 12:09

user3887366


1 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>
like image 164
Ulvi Avatar answered Sep 18 '26 02:09

Ulvi