src/app.html, inside <head> and above %sveltekit.head%. That template wraps every page, so every route is tracked. SvelteKit’s client-side navigation goes through the History API, which the script watches, so you do not need an afterNavigate callback.
You need your site’s public key, which starts with cs_pk_. Find it in your site’s settings under Tracking code. The key is safe to publish.
1
Add the tag to src/app.html
src/app.html
cs_pk_xxxxxxxx with your public key. Keep it a classic script with defer: type="module" does not work, because the script reads its options from its own tag.2
Turn on more tracking (optional)
Add attributes to the same tag:The switches in Settings, Tracking code add
src/app.html
data-outbound, data-downloads, data-vitals, data-errors and data-404 to the generated snippet. Leave Hash routing off: this framework routes with real paths, and data-hash only reads routes written after #. Script attributes lists every attribute the script reads, including data-exclude and data-domains, and what each one does.3
Deploy and confirm
Pages on
localhost, 127.0.0.1 and file:// are ignored, so a visit to vite dev is not counted. Deploy, then open your production site in a browser without an ad blocker.- In your browser’s developer tools, the Network tab shows a
POSTrequest tohttps://in.crispstats.com/eon the first load and on each client-side navigation. The collector answers202. - In CrispStats, your site’s Tracking code settings tab shows Receiving events. with the time of the last event.
data-debug to the tag and localhost to data-domains while you develop: every event is logged in the console and nothing is sent. Remove both before you ship. See localhost and testing.How client routing is counted
The script tracks a pageview on the first load, on everyhistory.pushState and replaceState, and on popstate (the back and forward buttons). The same URL twice in a row is one pageview, so goto() to the current page, or a replaceState that keeps the URL, does not add a view. On a client-side navigation the referrer is the previous page.
Preloading with data-sveltekit-preload-data fetches data without changing the URL, so it is not counted.
Send custom events
Call the global function from a component:src/lib/UpgradeButton.svelte
crispstats.d.ts from TypeScript in src/. It types every method of the global, and the queue stub there (in src/hooks.client.ts) keeps early calls from being lost.
The optional call (?.) keeps the button working when an ad blocker stops the script from loading. For clicks you can also use data-cs-event attributes and no JavaScript, see declarative events.
Next steps
Custom events
Track signups, clicks and other actions with properties.
Exclude traffic
Skip admin paths, staging hosts and your own browser.
Single-page apps
How client navigation, hash routing and engagement are tracked.