Google Analytics with SvelteKit
Date: 2022-05-29 | svelte | sveltekit | google-analytics |
Google Analytics provides visibility into how visitors interact with your website. In this post, we're going to show you how to integrate Google Analytics into your website built with SvelteKit.
Note: SvelteKit is my pick for Best Frontend Framework in 2022.
_Update 2022-10-11: This post has been updated to reflect SvelteKit's updated public api, namely template files being renamed from _FILE to +FILE.
Table of Contents
Google Analytics Measurement ID
Google Analytics gives you insights into how visitors use your website. The way it works is:
- Visitors go to your website
- Your website downloads the Google Analytics JavaScript library
- Your website logs information using the library
- Google Analytics aggregates the data for later analysis
GA uses a "Measurement ID" to identify which website is logging the data / how it should aggregate that data. So we need our Measurement ID before we can fully integrate with GA.
To find your Measurement ID:
- Navigate to the target Property
Admin > Data Streams
then select the target Data Stream- There should be a
MEASUREMENT ID
field with your ID - something likeG-ABCD123
Hold onto this Measurement ID -> we'll be using it later.
Note: Setting up a Google Analytics account and property is out of scope of this post but there's a lot of good documentation out there to use.
Google Analytics in SvelteKit
Now that we have a way to tell Google who we are and how we want them to aggregate our data, we need to actually send them data.
Download the Google Analytics library
The first step is to download the Google Analytics library into our site. We can do this using +layout.svelte
and the svelte:head
element.
// +layout.svelte
<svelte:head>
<script async src="https://www.googletagmanager.com/gtag/js"></script>
</svelte:head>
+layout.svelte
is the base template that every other page in thisroute
will use. Putting GA here will enable us to use it in every page in our SvelteKit site.svelte:head
is a special element in Svelte which allows us to target the output HTML'shead
tag which is useful for us when downloading external libraries.
Log to Google Analytics
Now that we have the library in our site, we need to configure it with the Measurement ID we retrieved earlier and log our data to it. We can put this in a script
tag inside +layout.svelte
so that it logs on every page load.
// +layout.svelte
<script>
try {
if(typeof window !== 'undefined'
&& window) {
const googleAnalyticsId = 'YOUR_MEASUREMENT_ID_HERE'
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', googleAnalyticsId);
}
} catch(error) {
console.error("Failed to initialize Analytics")
}
</script>
window
- We are checking forwindow
here so we don't fail in the case of SSR (Server-Side Rendering).
Updates: 2022-10-07 - Wrap analytics calling code in try / catch to fail gracefully.
Validating your Setup
Now that all our code is in place, we should validate that it's actually working! The best way to do this is through an E2E test of this functionality.
To validate your site's Google Analytics integration:
- Serve your website (localhost is fine)
- Navigate to it in a browser
- Monitor your site's Google Analytics
Reports
page
If it's working, you should see Users in Last 30 Minutes
> 0.
Here's an example of what a working integration would look like:
Google Analytics screenshot with a current viewer
Next Up:
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.