SvelteKit

Install Clamp in a SvelteKit app. Auto-pageviews from the root layout, server-side events from +server.ts, queryable by your AI agent via MCP.

Install

terminal
npm install @clamp-sh/analytics

Setup

Call init() inside onMount in your root +layout.svelte. This guarantees it runs in the browser only.

src/routes/+layout.svelte
<script>
  import { onMount } from "svelte"
  import { init } from "@clamp-sh/analytics"

  onMount(() => {
    init("proj_xxx")
  })
</script>

<slot />

Pageviews — including client-side navigations — are tracked automatically.

Track custom events

Import track from the main SDK entry and call it from any component:

src/components/SignupButton.svelte
<script>
  import { track } from "@clamp-sh/analytics"
</script>

<button on:click={() => track("signup_started", { plan: "pro" })}>
  Sign up
</button>

Properties must be flat string key-value pairs. See Events for limits and schema.

Server-side events

From a +server.ts route, use the /server entry with an API key:

src/routes/api/signup/+server.ts
import { init, track } from "@clamp-sh/analytics/server"
import { env } from "$env/static/private"

init({ projectId: "proj_xxx", apiKey: env.CLAMP_API_KEY })

export async function POST({ request }) {
  const { anonymousId } = await request.json()

  await track("signup_completed", {
    anonymousId,
    properties: { plan: "pro" },
  })

  return new Response(JSON.stringify({ ok: true }))
}

Pass anonymousId from the browser (via getAnonymousId()) to link server events to the visitor session.

Verify

  1. Deploy or open your app at a non-localhost URL (localhost is skipped by design).
  2. Navigate between a few pages.
  3. In your Clamp dashboard, pageviews should appear within ~5 seconds.
  4. DevTools → Network → filter for e/batch to confirm requests are sending.

Gotcha

Never call init() at the top level of a +layout.svelte script block or inside +layout.server.ts. Both can execute on the server where window doesn’t exist and init() will throw. onMount is the correct guard — it only runs in the browser.

Next step