Essay - Published: 2023.02.15 | fathom-analytics | sveltekit | tutorial |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
In this post we'll walk through how to use Fathom Analytics with a SvelteKit website.
Fathom Analytics is a simple, privacy-first web analytics service.
I like it because it's:
I like the service a lot and have been migrating my sites away from Google Analytics over to Fathom - more on that in a future post.
Want to try Fathom Analytics? Get $10 off your first Fathom purchase
Now that we understand what Fathom is, let's move to using Fathom Analytics in our SvelteKit site.
We'll use a Fathom Analytics embed to on our site to enable analytics every time a webpage is loaded. Each webpage has a unique ID that makes sure this data is logged to the right place so you can see it in your dashboard.
This HTML script code looks something like this:
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR_SITE_ID" defer></script>
Which loads a tiny bit of JavaScript into your webpage so it can log a user visited your page.
Now we just need to find YOUR_SITE_ID so Fathom logs this to the correct place.
If you're configuring a new site in Fathom, the easiest way to get your embed code is:
Site name, click NextSite ID or copy the HTML Embed CodeIf you have an existing site configured in Fathom, you can get your embed code by:
SettingsSites tabScript settings tabEmbed codeNow that we have our HTML embed code, we can implement it in our SvelteKit site.
For most analytics usecases we'll want to have analytics on every page. SvelteKit's layout pages provide a template that every other page in the subtree use. This makes it a great place to implement analytics.
So for this implementation, we'll use:
+layout.svelte - to add it to the "template" for the entire subtreesvelte:head - to add it to the resulting HTML head sectionSo in your layout file, this will look something like:
routes/+layout.svelte
<svelte:head>
<script src="https://cdn.usefathom.com/script.js" data-site="YOUR_SITE_ID" defer></script>
</svelte:head>
Remember: Replace YOUR_SITE_ID with your Fathom Analytics site id.
Theoretically this should work, but it's always good to test what we've built.
To test our Fathom Analytics integratoin with SvelteKit, we can:
You should now have analytics powered by Fathom working on your SvelteKit site!
If you'd like to get a full, runnable example project (including all source code) for a SvelteKit site with working Fathom integration, join the HAMINIONs membership. HAMINIONs get full source code access to all code examples I build and share in my tutorials.
If you want to try Fathom Analytics - Use this link to get $10 off your first Fathom bill.
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.