Chris Tam · Last updated 13 October 2026
SvelteKit uses route files under src/routes to define URLs. Heatmaps show where people click and how far they scroll on each of those pages, so you see which parts of a screen get used and which get skipped.
I turn on session replay for heatmaps, give each settings tab its own route, and create a heatmap ready to fill as traffic arrives. The complete setup on this page works without completing another tutorial.
What you'll build
A SvelteKit app that records session replay on every route, sends [Amplitude] Page Viewed with the same device_id as the replay, keeps the masking rules from the session replay page, and gives the Profile and Billing tabs of /settings their own routes, plus a click map in Amplitude for every /projects/[projectId] page. By the end you'll see a replay of your test session and a heatmap set up to fill in once traffic crosses the data threshold.
Prerequisites
- A SvelteKit 2.10 or later app with Svelte 5. The
initexport insrc/hooks.client.tsarrived in SvelteKit 2.10.
A Node.js 22.12+ (22.x) or Node.js 24 environment and pnpm for the SvelteKit 2 + Svelte 5 demo below. An existing app can use the same additions after merging them into its current configuration.
- An Amplitude project API key. In Amplitude, go to Settings > Projects > your project > General.
- Access to heatmaps in Amplitude. Any user with View permissions can create a heatmap; turning on heatmap capture for a project takes an Admin or Manager role.
Heatmaps are available on the Plus, Growth, and Enterprise plans, for customers with session replay; compare plans.
Amplitude recommends a separate development project for testing heatmaps, so your test clicks stay out of production data. Heatmap and session replay events don't count toward your event volume.
Use Node.js 22.12+ in the 22.x series, or Node.js 24, with pnpm. The complete demo pins SvelteKit 2 and Svelte 5 dependencies.
1. Install the SDK
I use the Browser Unified SDK installed with pnpm. Its initAll call accepts analytics and session replay options. The complete setup below includes the SDK dependency; if your app already initializes Amplitude, merge only the additions.
I start with the complete demo below. No earlier Build tutorial is required. In an existing app, merge the SDK and route additions into its current files; keep authentication, identity handling and other instrumentation. The setup block contains separate files: create each named file before running the terminal commands.
// -- package.json --
{
"name": "sveltekit-heatmaps",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"scripts": {
"dev": "vite dev",
"build": "svelte-kit sync && vite build",
"preview": "vite preview"
},
"dependencies": {
"@amplitude/unified": "1.1.42",
"@sveltejs/kit": "2.70.3",
"svelte": "5.57.2"
},
"devDependencies": {
"@sveltejs/adapter-auto": "6.1.1",
"@sveltejs/vite-plugin-svelte": "6.2.4",
"vite": "7.3.7",
"typescript": "5.9.3"
}
}
// -- pnpm-workspace.yaml --
minimumReleaseAge: 10080
trustPolicy: no-downgrade
// -- svelte.config.js --
import adapter from '@sveltejs/adapter-auto';
export default { kit: { adapter: adapter() } };
// -- vite.config.ts --
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({ plugins: [sveltekit()] });
// -- tsconfig.json --
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}
// -- src/app.html --
<!doctype html>
<html lang="en">
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />%sveltekit.head%</head>
<body data-sveltekit-preload-data="hover"><div style="display: contents">%sveltekit.body%</div></body>
</html>
// -- src/routes/+layout.svelte --
<script lang="ts">
let { children } = $props();
</script>
<nav>
<a href="/">Home</a>
<a href="/settings/profile">Profile</a>
<a href="/settings/billing">Billing</a>
<a href="/projects/demo-1">Sample project</a>
</nav>
{@render children()}
// -- src/routes/+page.svelte --
<h1>Local heatmap demo</h1>
<p>Use the navigation to exercise the tutorial.</p>mkdir sveltekit-heatmaps-demo
cd sveltekit-heatmaps-demo
# Create the named setup files shown on this page, then install:
pnpm install
# Start the app after adding the SDK and route files in the remaining steps.Already on @amplitude/analytics-browser to keep bundle size down? Add the Session Replay Browser SDK Plugin to your existing init instead of installing a second SDK. It takes the same options as the sessionReplay block in step 2.
Heatmaps need Session Replay Browser SDK Plugin 1.7.0 or later. The Verify section shows how to read the version your page actually runs.
SvelteKit only exposes env vars prefixed with PUBLIC_ to browser code. The project API key is public and its scope is limited to the minimum needed to ingest data, so shipping it to the browser is expected, but keep it out of source anyway.
PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
2. Initialize with session replay on
Session replay's default sample rate is 0, which records nothing. Setting sessionReplay.sampleRate above 0 turns recording on, and recording is what heatmaps are built from. For the clean demo, create src/hooks.client.ts with this version. In an existing app, merge only the sessionReplay additions into its current initialization. It keeps the masking rules from the session replay page, since heatmap backgrounds are replay snapshots and unmasked text would show up in them.
Keep any options you added on other SvelteKit pages, such as pageViews: { trackHistoryChanges: 'pathOnly' } from the web analytics page, and change only the sessionReplay block, which is all heatmaps need. If your file passes initAll to setAmplitudeReady (from /build/sveltekit-feature-flags or /build/sveltekit-guides-surveys), keep that wrapper around initAll, its import, and the setAmplitudeReady(null) line; without them, flags never fetch and the guides router never registers, with no error in the console.
import type { ClientInit } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { PUBLIC_AMPLITUDE_API_KEY } from '$env/static/public';
import * as amplitude from '@amplitude/unified';
export const init: ClientInit = () => {
if (!PUBLIC_AMPLITUDE_API_KEY) {
console.warn('PUBLIC_AMPLITUDE_API_KEY is not set; analytics is off.');
return;
}
void amplitude.initAll(PUBLIC_AMPLITUDE_API_KEY, {
// This tutorial does not load guides and surveys. Keep your existing engagement setup if you use it.
engagement: { skip: true },
analytics: {
autocapture: {
attribution: true,
pageViews: true,
sessions: true,
formInteractions: true,
fileDownloads: true,
elementInteractions: true,
},
},
sessionReplay: {
useWebWorker: false, // Explicitly use main-thread processing for this demo.
// Every session in `npm run dev`, about 1% in a production build.
sampleRate: dev ? 1 : 0.01,
// Adds [Amplitude] Session Replay Debug with an API key hash. Initial setup only.
debugMode: dev,
// From /build/sveltekit-session-replay. Keep your masking rules when you paste this file.
privacyConfig: {
maskSelector: ['[data-amp-mask]'],
blockSelector: ['[data-amp-block]'],
unmaskSelector: ['[data-amp-unmask]'],
},
},
});
};The root layout, entry point and routes needed for this demo are included in the complete setup and full code reference. In an existing app, keep its identity and sign-out code.
Why. Initializing more than once can leave replay and analytics events with different device or session IDs. Heatmaps still draw an unsegmented map in that case, but segment and cohort filters come back empty, because Amplitude can't join the clicks to your users. The client hook's init runs once per page load, in the browser only. Never add a second initAll in a layout's onMount or $effect, which run again whenever that layout mounts, or in a load function, which runs on the server.
Heatmap interactions come from session replay. This demo also enables elementInteractions for click events in product analytics. Leave pageUrlEnrichment at its default enabled setting so your custom events receive the current page URL.
Be deliberate about the sample rate. Every heatmap reflects only the sessions you captured, so at 0.01 a map is built from 1% of traffic and takes longer to cross the data threshold. Amplitude recommends starting low and raising the rate over a few days; capture stops for the month once your org's replay quota runs out. Session Replay Settings in Amplitude can also set the project's rate remotely, so check there when the rate you see doesn't match your code. Heatmap backgrounds show only what your masking lets through; read the SvelteKit session replay page before you raise the rate in production.
Guides and surveys initialize by default in the Unified SDK. This demo sets engagement: { skip: true } because it does not use them. Keep your current engagement configuration if your existing app does use them, and follow that SDK's CSP requirements.
3. Turn on heatmap capture in Amplitude
The SDK records replays, but the project decides whether heatmap data gets collected. In Amplitude, go to Settings > Organizational Settings > Session Replay Settings. The project list shows a session capture toggle and a heatmap capture toggle for each project. Turn both on for this project.
Select the project to open its Sampling control. A rate set there applies to the project without a deploy, which is the easier place to raise capture once heatmaps need more data.
4. Give each tab its own route
Heatmaps compute data per URL string, not per view. A tab bar that swaps content with a $state variable and {#if} blocks never changes the URL, so the Profile and Billing tabs of /settings end up in one heatmap, drawn over whichever tab the background happened to catch. SvelteKit fixes this with nested routes: each tab becomes its own folder under src/routes/settings, and the tab bar lives in a +layout.svelte that wraps them.
<script lang="ts">
let { children } = $props();
</script>
<section>
<h1>Settings</h1>
<nav>
<a href="/settings/profile">Profile</a>
<a href="/settings/billing">Billing</a>
</nav>
<!-- The active tab renders here. -->
{@render children()}
</section><h2>Profile</h2><h2>Billing</h2>Send /settings on its own to the first tab, so it never becomes a page of its own:
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = () => {
// No campaign links land here. For guards that can receive one, see withCampaign on /build/sveltekit-web-analytics.
redirect(307, '/settings/profile');
};The heatmap in step 5 targets a dynamic project route. If your app doesn't have a project screen yet, add a minimal one:
import type { PageLoad } from './$types';
export const load: PageLoad = ({ params }) => {
return { projectId: params.projectId };
};<script lang="ts">
let { data } = $props();
</script>
<h1>Project {data.projectId}</h1>The links and the redirect assume your app has no paths.base. If you set one in svelte.config.js, prefix them with base from $app/paths, for example href="{base}/settings/profile". These load functions only return route data; they never call the SDK. The settings layout nests inside the root layout shown in step 1. Keep any existing identity effect when merging into your app.
Now /settings/profile and /settings/billing get separate heatmaps, and each tab switch also sends its own [Amplitude] Page Viewed. The redirect runs in the load function before SvelteKit updates the URL, on a direct visit and on a client-side navigation alike, so /settings on its own never records a page view.
Why. Put the tab in the path, not in a query string such as /settings?tab=billing read from the page URL's searchParams. Heatmaps need the [Amplitude] Page URL property to match URLs, and that property is the page URL with query parameters removed, so /settings?tab=profile and /settings?tab=billing can land in the same heatmap. A path segment is unambiguous. Modals and drawers that don't change the URL also merge into the page underneath; if one matters, give it a route the same way.
Keep the trailingSlash page option (exported from a +layout.ts or +page.ts, default 'never') as it is once heatmaps are collecting. Heatmap data is keyed by the URL string, so switching from /settings/billing to /settings/billing/ mid-stream splits one page's data across two URLs, and an Exact match filter has to use whichever form your app serves.
5. Create your first heatmap
Heatmaps appear after Amplitude collects enough replay click data across your site: at least 10 separate pages, with about 500 tracked replay clicks on each page. These thresholds are approximate. Create the heatmap now and it fills in once traffic crosses them.
- In Amplitude, click Heatmaps in the left navigation, then + New Heatmap.
- Choose Click map. You can switch to a selector map or scroll map at any time.
- Select the URL.
src/routes/projects/[projectId]gives every project its own URL, so use Pattern match withhttps://your-domain.com/projects/*to combine them into one map. Use Exact match for a single page, such ashttps://your-domain.com/settings/billing, and Starts with for a section, such ashttps://your-domain.com/settings. - Optionally pick a segment of users by user property or cohort.
- Pick a device type. Heatmaps group data into four screen-width buckets: greater than 1440px, 900 to 1440px, 500 to 899px, and less than 500px. A responsive layout that collapses its nav into a menu below a CSS breakpoint looks different in each bucket, and the background and the click data must fall in the same one.
- Choose a background. Each heatmap generates eight, taken from the page states with the most actions. Skip any that caught an open modal or a loading spinner.
Once your data meets the thresholds, Amplitude also creates a few heatmaps automatically for your highest-traffic pages. You can delete them; they aren't recreated.
Keep personal data out of URL paths. If your application needs URL redaction, follow the linked URL filtering guide and verify the integration in a development project before production capture. Do not assume masking page text also redacts its URL.
MCP. Working in Cursor or Claude Code? Amplitude's MCP server lets your agent read your project's existing event taxonomy before it adds track calls near a heatmap hotspot, so new events match names you already use instead of inventing planUpgraded next to Plan Upgraded. Set up the MCP server.
Verify it worked
A development session can't reach the heatmap data threshold, so verification stops at confirming that replays arrive from a new enough SDK and that each tab has its own URL. Run pnpm dev, open http://localhost:5173 in a fresh window, click between /settings/profile, /settings/billing, and a project page, then check in this order:
- Network tab. Filter for
amplitude. You should see event uploads toapi2.amplitude.comreturning200, a request tosr-client-cfg.amplitude.com, and replay uploads toapi-sr.amplitude.com. None of them come from the server render; they start once the page loads in the browser. - Ingestion Debugger. In Amplitude, click Data, select Sources, then open the Ingestion Debugger tab. The successful requests chart should show your uploads. It shows counts, not individual events.
User lookup. Go to Users > User Profiles and search the device ID shown by the Instrumentation Explorer extension. Trigger an interaction after initialization and inspect its event properties for [Amplitude] Session Replay ID. Events appear in ten seconds to one minute; replays are generally available about five minutes after a session begins. A local-only test does not establish ingestion or playback.
- Session Replay debug panel. In the Instrumentation Explorer Chrome extension, turn on the Session Replay debug panel. It shows the current replay ID, the session replay SDK and plugin versions, the sample rate, and the default and effective masking settings. The plugin version must be 1.7.0 or later, and the sample rate must not be
0. - Heatmaps. Open the heatmap from step 5. In a development project it shows "No heatmap available" until the thresholds are met. After you deploy, confirm the live site serves the updated SDK, not only your local build.
Troubleshooting
The heatmap is blank or says "No heatmap available"
Work through the causes in order: Amplitude is still processing new replay data (a few minutes after install), the URL filter doesn't match URLs in your events, the deployed site runs a session replay plugin older than 1.7.0, or traffic hasn't reached about 500 replay clicks on each of 10 pages. If [Amplitude] Page URL was hidden, restore it in Data > Properties.
Every tab on a screen shows up in one heatmap
The tabs share a URL. Move each one to its own route folder as in step 4. A tab kept in a query string can merge too, because [Amplitude] Page URL drops query parameters; move it into the path.
No replays at all, even with a sample rate of 1
For a strict CSP, retain the policy your app needs and allow the complete endpoint set for its region. US connect-src: https://api2.amplitude.com https://api-sr.amplitude.com https://sr-client-cfg.amplitude.com. EU connect-src: https://api.eu.amplitude.com https://api-sr.eu.amplitude.com https://sr-client-cfg.eu.amplitude.com, with serverZone set to EU at the top level of initAll options. This demo explicitly sets useWebWorker to false. If your existing app enables it, allow worker-src blob: too. The demo skips guides and surveys; if your app enables them, also apply their documented CSP requirements. A blocked remote-configuration request prevents replay capture.
A background shows no data
The background's viewport width falls in a different screen-width bucket from your recorded sessions. Use Change Screenshot > From a Replay and pick a screenshot taken at a width where your data exists.
Segment or cohort filters return nothing
Replay and analytics events carry different device_id values, so Amplitude can't join clicks to users. Look for a second initAll or init call, for example in a layout's onMount, or a standalone session replay SDK running beside your analytics. Keep the single init in src/hooks.client.ts.
"Heatmaps isn't available for your organization"
Your organization predates Amplitude's current packaging and needs manual enablement. Contact Amplitude Support.
Full code reference
Every file needed for the standalone demo is included below. Split the block at its filename comments. For an existing app, merge changes into its files and keep any existing authentication, identity, routes and other Amplitude configuration.
// -- src/hooks.client.ts --
import type { ClientInit } from '@sveltejs/kit';
import { dev } from '$app/environment';
import { PUBLIC_AMPLITUDE_API_KEY } from '$env/static/public';
import * as amplitude from '@amplitude/unified';
export const init: ClientInit = () => {
if (!PUBLIC_AMPLITUDE_API_KEY) {
console.warn('PUBLIC_AMPLITUDE_API_KEY is not set; analytics is off.');
return;
}
void amplitude.initAll(PUBLIC_AMPLITUDE_API_KEY, {
// This tutorial does not load guides and surveys. Keep your existing engagement setup if you use it.
engagement: { skip: true },
analytics: {
autocapture: {
attribution: true,
pageViews: true,
sessions: true,
formInteractions: true,
fileDownloads: true,
elementInteractions: true,
},
},
sessionReplay: {
useWebWorker: false, // Explicitly use main-thread processing for this demo.
// Every session in `npm run dev`, about 1% in a production build.
sampleRate: dev ? 1 : 0.01,
// Adds [Amplitude] Session Replay Debug with an API key hash. Initial setup only.
debugMode: dev,
// From /build/sveltekit-session-replay. Keep your masking rules when you paste this file.
privacyConfig: {
maskSelector: ['[data-amp-mask]'],
blockSelector: ['[data-amp-block]'],
unmaskSelector: ['[data-amp-unmask]'],
},
},
});
};
// -- src/routes/settings/+layout.svelte --
<script lang="ts">
let { children } = $props();
</script>
<section>
<h1>Settings</h1>
<nav>
<a href="/settings/profile">Profile</a>
<a href="/settings/billing">Billing</a>
</nav>
<!-- The active tab renders here. -->
{@render children()}
</section>
// -- src/routes/settings/profile/+page.svelte --
<h2>Profile</h2>
// -- src/routes/settings/billing/+page.svelte --
<h2>Billing</h2>
// -- src/routes/settings/+page.server.ts --
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = () => {
// No campaign links land here. For guards that can receive one, see withCampaign on /build/sveltekit-web-analytics.
redirect(307, '/settings/profile');
};
// -- src/routes/projects/[projectId]/+page.ts --
import type { PageLoad } from './$types';
export const load: PageLoad = ({ params }) => {
return { projectId: params.projectId };
};
// -- src/routes/projects/[projectId]/+page.svelte --
<script lang="ts">
let { data } = $props();
</script>
<h1>Project {data.projectId}</h1>
// -- package.json --
{
"name": "sveltekit-heatmaps",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"scripts": {
"dev": "vite dev",
"build": "svelte-kit sync && vite build",
"preview": "vite preview"
},
"dependencies": {
"@amplitude/unified": "1.1.42",
"@sveltejs/kit": "2.70.3",
"svelte": "5.57.2"
},
"devDependencies": {
"@sveltejs/adapter-auto": "6.1.1",
"@sveltejs/vite-plugin-svelte": "6.2.4",
"vite": "7.3.7",
"typescript": "5.9.3"
}
}
// -- pnpm-workspace.yaml --
minimumReleaseAge: 10080
trustPolicy: no-downgrade
// -- svelte.config.js --
import adapter from '@sveltejs/adapter-auto';
export default { kit: { adapter: adapter() } };
// -- vite.config.ts --
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({ plugins: [sveltekit()] });
// -- tsconfig.json --
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}
// -- src/app.html --
<!doctype html>
<html lang="en">
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />%sveltekit.head%</head>
<body data-sveltekit-preload-data="hover"><div style="display: contents">%sveltekit.body%</div></body>
</html>
// -- .env --
PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
// -- src/routes/+layout.svelte --
<script lang="ts">
let { children } = $props();
</script>
<nav>
<a href="/">Home</a>
<a href="/settings/profile">Profile</a>
<a href="/settings/billing">Billing</a>
<a href="/projects/demo-1">Sample project</a>
</nav>
{@render children()}
// -- src/routes/+page.svelte --
<h1>Local heatmap demo</h1>
<p>Use the navigation to exercise the tutorial.</p>
// -- static/avatar.svg --
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#0052F2"/><circle cx="16" cy="12" r="6" fill="white"/><path d="M5 31c0-14 22-14 22 0" fill="white"/></svg>Hand it to your agent
Prefer to have Cursor, Claude Code, or Codex CLI do the wiring? This prompt points the agent at this page and pins the decisions that matter.
Follow https://amplitude.com/build/sveltekit-heatmaps using only the complete setup and Full code reference on this page. Do not require another tutorial. Split the reference at filename comments and create every required file. For an existing app, merge additions and keep authentication, identity, routes and other instrumentation. Use the existing root component/layout file. Initialize Amplitude once in the init export of src/hooks.client.ts. Keep the empty-key guard and the existing ready-promise wrapper if present. Use development sample rate 1 and production 0.01, with debugMode enabled only in development. This option adds diagnostic information; current recording has no focus gate. Keep the masking selectors and do not place personal data in HTML attributes. Use the page's demo routes to exercise the behavior. Keep engagement.skip true for this demo, or retain the existing engagement configuration and its required CSP if the app uses guides and surveys. Check the full endpoint set for the selected region. Build the actual app and run its Verify steps; report build, local browser behavior and live service results separately. Do not claim ingestion or playback from a mocked test.Frequently asked questions
Do I need to finish the product analytics tutorial first?
No. This page includes the setup and complete demo files. In an existing app, merge the additions into the SDK initialization you already have.
Does debugMode bypass a focus check?
Current SDK recording has no focus gate. debugMode adds a diagnostic event property containing an API key hash. Use it for initial setup and keep it off in production.
What can I verify without an Amplitude project?
You can check builds, navigation, DOM attributes and local browser behavior. Successful ingestion, replay playback and processed heatmaps need a configured project and separate verification.
What this unlocks
- Session replay, already on from step 2, lets you select an area of a click map and watch the sessions behind those clicks.
- Product analytics can chart
[Amplitude] Page Viewedfor/settings/billingagainst your upgrade event to see whether the tab you just mapped converts. - Feature Experiment, bundled in
@amplitude/unified, can test a new billing layout, and a heatmap per variant shows how the clicks moved. - Guides and surveys, also bundled, can point users to a button the click map shows they miss.
Next steps
Reference docs
Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.