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

1

Get Your Tracking Script

Navigate to your Databuddy dashboard to get your tracking code snippet:

html
<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.

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 Databuddy tracking snippet into the <head> section, usually before %sveltekit.head% or just after it.

src/app.htmlhtml
<!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.

4

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.

Custom Event Tracking

Track custom events from any Svelte component within your SvelteKit app:

svelte
<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:

src/routes/+layout.sveltesvelte
<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:

html
<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:

svelte
<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:

html
<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:

svelte
<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:

src/routes/contact/+page.server.tstypescript
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:

svelte
<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:

src/routes/pricing/+page.sveltesvelte
<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:

bash
# Install the Node SDK
npm install @databuddy/sdk
src/lib/databuddy.tstypescript
import { 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:

.envbash
PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here
DATABUDDY_CLIENT_ID=your-client-id-here
DATABUDDY_CLIENT_SECRET=your-client-secret-here

Then use them in your code:

src/app.htmlhtml
<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.html in the <head> section
  • Check browser console for errors
  • Ensure your Client ID is correct
  • Clear browser cache and reload

Events Not Tracking

  • Confirm window.databuddy exists 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 afterNavigate from $app/navigation for manual tracking
  • Check that SvelteKit's client-side navigation is working correctly

SSR Issues

  • Never call window.databuddy during SSR (server-side rendering)
  • Always wrap tracking calls in typeof window !== 'undefined' checks
  • Use onMount or afterNavigate for client-only tracking

Need help with your SvelteKit integration? Contact us at help@databuddy.cc.

How is this guide?