Jo Does Tech
Jo Does Tech
Jul 3, 2022

How to add analytics for sveltekit via gtag.js (Google Analytics).

Set up a Google Analytics account (free).

For this guide you first need a Google account and will then need to sign up for Google Analytics.

Once you have an account, you will need to set up a property/web-app for your SvelteKit application. You should find a section that describes set up and tagging instructions. There you will find the following code snippet (you will have a different ID):

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

    gtag('config', 'G-TZ3NXQQW1C');

This is suitable for a plain web application, but is not ideal for modern frameworks/libraries such as SvelteKit, Next.js, React, Angular and Vue. We will need to make some adjustments to include it in our SvelteKit application.

Adding gtag.js to your SvelteKit application.


Create a new component called Gtag.svelte:

<script lang="ts">
    import { browser } from '$app/env';
    export let id: string;

    if (browser) {
        window.dataLayer = window.dataLayer || [];
        window.gtag = function gtag(): void {
        window.gtag('js', new Date());
        window.gtag('config', id);

    <script async src="{id}"></script>

You can then import your component and use it as follows:

<Gtag id="G-TZ3NXQQW1C" />

I put the above code in my main layout file. Ensuring it is present in all pages throughout my application.


We have set up a prop to input the ID for the application, the ID provided by Google Analytics.

We only want to run the gtag.js JavaScript if the code is running in the users browser. By default SvelteKit uses server side rendering (SSR). This means the page is first rendered on the backend, which is great for this like SEO, but more challenging for other basic tasks such as this. Fortunately SvelteKit and most other SSR frameworks come with the ability to check if code is being run on the server or the browser.

I use TypeScript, as it really helps me to write clear and scalable code. I had to add a couple typings for the above example to work:

declare interface Window {
  dataLayer?: IArguments[];
  gtag?: (...args: any[]) => void;

You should now have successfully set up your SvelteKit application with Google Analytics (gtag.js).

Let me know in the comments if you had any issues.