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
npm install @clamp-sh/analyticsSetup
Call init() inside onMount in your root +layout.svelte. This guarantees it runs in the browser only.
<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:
<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:
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
- Deploy or open your app at a non-localhost URL (localhost is skipped by design).
- Navigate between a few pages.
- In your Clamp dashboard, pageviews should appear within ~5 seconds.
- DevTools → Network → filter for
e/batchto 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.