SvelteKit
This guide explains how to integrate Databuddy with your SvelteKit application for analytics tracking.
How to Add Databuddy to Your SvelteKit App
The recommended method for SvelteKit is to add the Databuddy tracking script directly to your src/app.html file. This ensures the script is loaded early on all pages.
Adding to src/app.html
Get Your Tracking Script
Navigate to your Databuddy dashboard to get your tracking code snippet:
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id="YOUR_CLIENT_ID"
async
></script>Replace YOUR_CLIENT_ID with your actual Client ID.
Locate Your app.html File
In a SvelteKit project, this file is typically located at src/app.html.
Add the Snippet to app.html
Open src/app.html and paste the Databuddy tracking snippet into the <head> section, usually before %sveltekit.head% or just after it.
<!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" />
<!-- Databuddy Tracking Snippet -->
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id="YOUR_CLIENT_ID"
async
></script>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>Ensure YOUR_CLIENT_ID is replaced with your actual Client ID.
Verify Installation
Deploy your application and check your Databuddy dashboard for incoming data. You can also inspect your browser's network tab to confirm the script is loaded.
SPA Page View Tracking: Databuddy automatically tracks route changes in SvelteKit applications. If page views aren't tracked correctly after navigation (which is uncommon), you can 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.databuddy) {
window.databuddy.screenView({
path: window.location.pathname
});
}
});Test the default behavior first, as manual tracking is usually not needed.
Custom Event Tracking
Track custom events from any Svelte component within your SvelteKit app:
<script>
function handleAction() {
if (typeof window !== 'undefined' && window.databuddy) {
window.databuddy.track('button_click', {
component: 'MySvelteKitComponent',
button_id: 'cta-button'
});
}
}
</script>
<button on:click={handleAction}>
Perform Action
</button>Always check typeof window !== 'undefined' before accessing window.databuddy as SvelteKit components can also run on the server during SSR.
Tracking Route Changes
For more control over route tracking, use SvelteKit's navigation lifecycle:
<script>
import { afterNavigate } from '$app/navigation';
import { page } from '$app/stores';
afterNavigate(() => {
if (typeof window !== 'undefined' && window.databuddy) {
window.databuddy.screenView({
path: $page.url.pathname,
search: $page.url.search
});
}
});
</script>
<slot />Using Data Attributes
Enable automatic tracking with data attributes by adding this to your script tag:
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id="YOUR_CLIENT_ID"
data-track-attributes
async
></script>Then add data-track attributes directly to elements in your Svelte components:
<button
data-track="cta_click"
data-button-type="primary"
on:click={handleClick}
>
Get Started
</button>
<a
href="/pricing"
data-track="pricing_link_click"
data-link-location="header"
>
View Pricing
</a>Configuration Options
Enable additional tracking features:
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id="YOUR_CLIENT_ID"
data-track-attributes
data-track-outgoing-links
data-track-interactions
data-track-performance
data-track-web-vitals
data-track-errors
data-track-scroll-depth
async
></script>Common Use Cases
Form Submissions
Track form submissions in SvelteKit:
<script>
import { enhance } from '$app/forms';
function handleSubmit() {
if (typeof window !== 'undefined' && window.databuddy) {
window.databuddy.track('form_submit', {
form_type: 'contact',
form_id: 'contact-form'
});
}
}
</script>
<form method="POST" use:enhance={handleSubmit}>
<!-- form fields -->
<button type="submit">Submit</button>
</form>Server Actions
Track events from server actions:
import { fail } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
default: async ({ request }) => {
const data = await request.formData();
// Your form processing logic here
// Note: Server-side tracking requires the Node SDK
// Client-side tracking happens automatically via the script tag
return { success: true };
}
};Then track on the client side after successful submission:
<script>
import { enhance } from '$app/forms';
function handleResult({ result }) {
if (result.type === 'success' && typeof window !== 'undefined' && window.databuddy) {
window.databuddy.track('form_submit_success', {
form_type: 'contact'
});
}
}
</script>
<form method="POST" use:enhance={handleResult}>
<!-- form fields -->
</form>Page-Specific Tracking
Track events on specific pages:
<script>
import { onMount } from 'svelte';
onMount(() => {
if (typeof window !== 'undefined' && window.databuddy) {
window.databuddy.track('pricing_page_view', {
page_path: window.location.pathname
});
}
});
function trackPlanClick(planName) {
if (typeof window !== 'undefined' && window.databuddy) {
window.databuddy.track('plan_clicked', {
plan_name: planName,
page_path: window.location.pathname
});
}
}
</script>
<button on:click={() => trackPlanClick('pro')}>
Choose Pro Plan
</button>Server-Side Tracking
For server-side tracking in SvelteKit, use the Databuddy Node SDK:
# Install the Node SDK
npm install @databuddy/sdkimport { Databuddy } from '@databuddy/sdk/node';
export const databuddy = new Databuddy({
clientId: process.env.DATABUDDY_CLIENT_ID!,
clientSecret: process.env.DATABUDDY_CLIENT_SECRET!
});
// Track server-side events
export function trackServerEvent(eventName: string, properties?: Record<string, unknown>) {
return databuddy.track({
eventName,
properties,
anonymousId: 'server-event', // Use appropriate identifier
});
}Environment Variables
Store your Client ID in environment variables:
PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here
DATABUDDY_CLIENT_ID=your-client-id-here
DATABUDDY_CLIENT_SECRET=your-client-secret-hereThen use them in your code:
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id="%env.PUBLIC_DATABUDDY_CLIENT_ID%"
async
></script>Troubleshooting
Script Not Loading
- Verify the script is in
src/app.htmlin the<head>section - Check browser console for errors
- Ensure your Client ID is correct
- Clear browser cache and reload
Events Not Tracking
- Confirm
window.databuddyexists before calling tracking methods - Always check
typeof window !== 'undefined'for SSR safety - Check browser console for any errors
- Verify events appear in your Databuddy dashboard after 2-3 minutes
Route Changes Not Tracked
- Databuddy automatically tracks route changes in SvelteKit
- If needed, use
afterNavigatefrom$app/navigationfor manual tracking - Check that SvelteKit's client-side navigation is working correctly
SSR Issues
- Never call
window.databuddyduring SSR (server-side rendering) - Always wrap tracking calls in
typeof window !== 'undefined'checks - Use
onMountorafterNavigatefor client-only tracking
Need help with your SvelteKit integration? Contact us at help@databuddy.cc.
How is this guide?