How to integrate Google Analytics with SvelteKit and TypeScript

How to integrate Google Analytics with SvelteKit and TypeScript

monitor screengrab

If you’re working with SvelteKit and TypeScript and wondering how to integrate Google Analytics into your project, this article is for you. Let’s break down the process step-by-step:

1. Setting up the Svelte Component

Create a Svelte component, GoogleAnalytics.svelte, which will help initialize the Google Analytics configuration. This component is intended to be integrated into your SvelteKit application’s layout.

TypeScript
<script lang="ts">
	import { browser } from '$app/environment';
  export let id: string;
 
	if (browser) {
    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>

This script checks if we’re running in the browser context using browser from $app/environment. If so, it sets up Google Analytics. The id is passed as a prop to the component, allowing flexibility for different GA tracking IDs.

2. TypeScript Configuration

To ensure smooth compatibility with TypeScript, you need to extend the Window interface with the properties you’re adding in the Svelte component. This way, TypeScript knows about these new properties and won’t complain about potential errors.

TypeScript
declare interface Window {
	dataLayer: IArguments[];
	
	/* eslint-disable @typescript-eslint/no-explicit-any */
	gtag?: (...args: any[]) => void;
}

3. Integrating into Your SvelteKit App

Now, to integrate the Google Analytics component into your SvelteKit app, you’ll want to import and use it in your main layout, preferably in a file like src/routes/+layout.svelte.

TypeScript
<script>
	import GoogleAnalytics from '$lib/GoogleAnalytics.svelte';
</script>

<GoogleAnalytics id="YOUR-GA-ID"/>

Replace YOUR-GA-ID with your Google Analytics ID. Or import it using environment variables.

Conclusion

With the Svelte component and TypeScript configurations in place, integrating Google Analytics with your SvelteKit application is straightforward. Now, you can take advantage of the insights Google Analytics offers to understand your users better and improve your site based on data-driven decisions.

Share this content:

Leave a Reply

Your email address will not be published. Required fields are marked *