Integrations

SvelteKit

Add Databuddy to src/app.html and every page and client-side navigation in your SvelteKit app is recorded.

Add Databuddy

src/app.html
<head>
  <meta charset="utf-8" />
  <script
    src="https://cdn.databuddy.cc/databuddy.js"
    data-client-id="%sveltekit.env.PUBLIC_DATABUDDY_CLIENT_ID%"
    data-track-web-vitals
    data-track-errors
    crossorigin="anonymous"
    async
  ></script>
  %sveltekit.head%
</head>
.env
PUBLIC_DATABUDDY_CLIENT_ID=YOUR_CLIENT_ID

Your Client ID is in the dashboard under your website's Settings → General. Client-side navigation is tracked automatically, so you don't need afterNavigate.

Track an event

src/routes/pricing/+page.svelte
<script>
  import { track } from "@databuddy/sdk";
</script>

<button onclick={() => track("plan_selected", { plan: "pro" })}>
  Choose Pro
</button>

track() skips the server render and waits for the tracker in the browser, so it's safe anywhere.

Track a form after it succeeds

src/routes/contact/+page.svelte
<script>
  import { enhance } from "$app/forms";
  import { track } from "@databuddy/sdk";

  const onSubmit = () => async ({ result, update }) => {
    if (result.type === "success") {
      track("contact_form_sent");
    }
    await update();
  };
</script>

<form method="POST" use:enhance={onSubmit}>
  <!-- fields -->
</form>

Send an event from the server

Add an API key in Organization settings → API keys and add it to .env as DATABUDDY_API_KEY.

src/lib/server/databuddy.ts
import { Databuddy } from "@databuddy/sdk/node";
import { DATABUDDY_API_KEY } from "$env/static/private";
import { PUBLIC_DATABUDDY_CLIENT_ID } from "$env/static/public";

export const databuddy = new Databuddy({
  apiKey: DATABUDDY_API_KEY,
  websiteId: PUBLIC_DATABUDDY_CLIENT_ID,
});
src/routes/contact/+page.server.ts
import { databuddy } from "$lib/server/databuddy";

export const actions = {
  default: async () => {
    await databuddy.track({ name: "contact_form_sent", source: "server" });
    await databuddy.flush();
    return { success: true };
  },
};

Call flush() before returning on serverless hosts, so the event is sent before the function stops.

How is this guide?