Skip to Content
🚀 We just launched! Please star us on Github!
DocumentationGuidesSvelteSvelteKit

SvelteKit

This guide explains how to integrate Rybbit with your SvelteKit application for analytics tracking.

How to Add Rybbit to Your SvelteKit App

The recommended and most straightforward method for SvelteKit is to add the Rybbit tracking script directly to your src/app.html file. This ensures the script is loaded early on all pages.

Adding to src/app.html

1. Retrieve Your Tracking Script

Navigate to your Rybbit dashboard to obtain your code snippet:

<script src="https://app.rybbit.io/api/script.js" data-site-id="YOUR_SITE_ID" async defer ></script>

Replace YOUR_SITE_ID with your actual Site ID.

2. Locate Your app.html File

In a SvelteKit project, this file is typically located at src/app.html.

3. Add the Snippet to app.html

Open src/app.html and paste the Rybbit tracking snippet into the <head> section, usually before %sveltekit.head% or just after it.

src/app.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%sveltekit.assets%/favicon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- Rybbit Tracking Snippet --> <script src="https://app.rybbit.io/api/script.js" data-site-id="YOUR_SITE_ID" async defer ></script> %sveltekit.head% </head> <body data-sveltekit-preload-data="hover"> <div style="display: contents">%sveltekit.body%</div> </body> </html>

Ensure YOUR_SITE_ID is replaced.

4. Verify Installation

Deploy your application and check your Rybbit dashboard for incoming data.

SPA Page View Tracking: Rybbit’s script is designed to automatically track route changes in SvelteKit applications. If page views aren’t tracked correctly after navigation (which is uncommon), you might need to manually trigger them using the afterNavigate lifecycle function:

// In a layout or page component import { afterNavigate } from '$app/navigation'; afterNavigate(() => { if (typeof window !== 'undefined' && window.rybbit) { window.rybbit.trackPageview(); } });

Test the default behavior first.

Custom Event Tracking

From any Svelte component within your SvelteKit app, you can track custom events:

<script> function handleAction() { if (typeof window !== 'undefined' && window.rybbit) { window.rybbit.trackEvent('user_action_sveltekit', { component: 'MySvelteKitComponent' }); } } </script> <button on:click={handleAction}>Perform SvelteKit Action</button>

Always check typeof window !== 'undefined' before accessing window.rybbit as SvelteKit components can also run on the server.

Last updated on
Rybbit
Copyright 2025 © Rybbit.