JavaScript frameworks
Add Loogika to SvelteKit
SvelteKit renders every page through one HTML shell, the file src/app.html. You paste the Loogika tag into the head of that file, and the script loads on every route. Client-side navigation is counted as pageviews without a router hook.
Last updated .
What do you need before you start?
Copy your script tag from Site Settings in Loogika, under the Tracking Script tab. It looks like this, with your own 12-character site ID in place of YOUR_SITE_ID:
<script src="https://app.loogika.com/api/script.js?siteId=YOUR_SITE_ID" defer></script>
How do you add Loogika to src/app.html?
Open src/app.html and paste the tag inside the head, next to the %sveltekit.head% placeholder. The head of the file then looks like this:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://app.loogika.com/api/script.js?siteId=YOUR_SITE_ID" defer></script>
%sveltekit.head%
</head>
Does Loogika track SvelteKit navigation?
Yes. The SvelteKit router changes the address without a full page load, and Loogika records each of those changes as a pageview. The script waits 500 milliseconds after a route change before it sends the pageview.
Route tracking depends on the SPA Navigation setting in Site Settings, which is on by default. With the setting turned off, you record navigation yourself with afterNavigate in the root layout, src/routes/+layout.svelte:
<script>
import { afterNavigate } from "$app/navigation";
afterNavigate(({ type }) => {
if (type !== "enter" && window.loogika) {
window.loogika.pageview();
}
});
</script>
SvelteKit reports the first page load with the type enter, and the code skips it. Test the default behaviour before you add this code.
How do you track custom events in SvelteKit?
Any Svelte component can call window.loogika.event() with an event name and optional properties. SvelteKit components also run on the server, where window does not exist, so check for it first.
<script>
function handleAction() {
if (typeof window !== "undefined" && window.loogika) {
window.loogika.event("user_action", { component: "ActionButton" });
}
}
</script>
<button onclick={handleAction}>Perform action</button>
The example uses the event attributes of Svelte 5. On Svelte 4, write on:click={handleAction} in place of onclick={handleAction}.
A plain click needs no JavaScript at all. Add data-loogika-event="user_action" to the button, as the custom events guide describes.
How do you check that Loogika is installed?
Load your app in a fresh browser tab and visit a few pages. The pageviews show up in the Loogika dashboard within a few seconds.
If nothing arrives, look for script.js?siteId= in the page source. The browser Network tab should show script.js with status 200 and requests to /api/track. The script troubleshooting page covers ad blockers and wrong site IDs.