Chapter 146 · Integration Sveltekit
Subchapter 146.7
references/svelte.mdMarkdown7 KBView on GitHub
PostHog makes it easy to get data about traffic and usage of your Svelte app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.
This guide walks you through integrating PostHog into your SvelteKit app using the JavaScript Web (opens in a new tab) and Node.js (opens in a new tab) SDKs.
Install PostHog for Svelte in seconds with our wizard by running this prompt with LLM coding agents (opens in a new tab) like Cursor and Bolt, or by running it in your terminal.
npx @posthog/wizard@latest
Or, to integrate manually, continue with the rest of this guide.
Install posthog-js using your package manager:
PostHog AI
npm install --save posthog-jsyarn add posthog-jspnpm add posthog-jsbun add posthog-jsThen, if you haven’t created a root layout (opens in a new tab) already, create a new file called +layout.js in your src/routes folder In this file, check the environment is the browser, and initialize PostHog if so. You can get both your API key and instance address in your project settings (opens in a new tab).
routes/+layout.js
PostHog AI
import posthog from 'posthog-js'
import { browser } from '$app/environment';
export const load = async () => {
if (browser) {
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
defaults: '2026-01-30',
})
}
return
};Identifying users is required. Call
posthog.identify('your-user-id')after login to link events to a known user. This is what connects frontend event captures, session replays (opens in a new tab), LLM traces (opens in a new tab), and error tracking (opens in a new tab) to the same person — and lets backend events link back too.See our guide on identifying users (opens in a new tab) for how to set this up.
❗️ If you intend on using session replays with a server-side rendered Svelte app ensure that your asset URLs are configured to be relative (opens in a new tab).
Set up a reverse proxy (recommended)
We recommend setting up a reverse proxy (opens in a new tab), so that events are less likely to be intercepted by tracking blockers.
We have our own managed reverse proxy service (opens in a new tab), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy.
If you don’t want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare (opens in a new tab), AWS Cloudfront (opens in a new tab), and Vercel (opens in a new tab).
Grouping products in one project (recommended)
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it’s best to install PostHog on them all and group them in one project (opens in a new tab).
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
Add IPs to Firewall/WAF allowlists (recommended)
For certain features like heatmaps (opens in a new tab), your Web Application Firewall (WAF) may be blocking PostHog’s requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site.
EU: 3.75.65.221, 18.197.246.42, 3.120.223.253
US: 44.205.89.55, 52.4.194.122, 44.208.188.173
These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots).
Install posthog-node using your package manager:
PostHog AI
npm install posthog-node --saveyarn add posthog-nodepnpm add posthog-nodebun add posthog-nodeThen, initialize the PostHog Node client where you’d like to use it on the server side. For example, in a load function (opens in a new tab):
routes/+page.server.js
PostHog AI
import { PostHog } from 'posthog-node';
export async function load() {
const posthog = new PostHog('<ph_project_token>', { host: 'https://us.i.posthog.com' });
posthog.capture({
distinctId: 'distinct_id_of_the_user',
event: 'event_name',
})
await posthog.shutdown()
}Note: Make sure to always call
posthog.shutdown()after capturing events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately.
To use client-side feature flags, import PostHog into your Svelte component and check if the feature is enabled (while ensuring the code only runs in the browser).
routes/+page.svelte
PostHog AI
<script>
import posthog from 'posthog-js'
import { browser } from '$app/environment'
import { onMount } from 'svelte'
let coolFeature = $state(false)
onMount(() => {
if (browser) {
coolFeature = posthog.isFeatureEnabled('cool-feature')
}
})
</script>
{#if coolFeature}
<p>Welcome to the cool feature!</p>
{/if}To use server-side feature flags, import PostHog into your SvelteKit load function and check if the feature is enabled.
routes/+page.server.js
PostHog AI
import { PostHog } from 'posthog-node';
const client = new PostHog(
'<ph_project_token>',
{ host: 'https://us.i.posthog.com' }
);
export async function load() {
const distinctId = 'distinct_id_of_the_user';
const megaFeature = await client.isFeatureEnabled(
'mega-feature',
distinctId
);
return {
megaFeature
};
}See our JavaScript Web (opens in a new tab) and Node (opens in a new tab) docs for more details.
By default, Svelte uses relative asset paths (opens in a new tab) during server-side rending. This causes issues with PostHog’s ability to record sessions.
To fix this, set the config to not use relative paths in svelte.config.js:
JavaScript
PostHog AI
kit: {
paths: {
relative: false,
},
},For any technical questions for how to integrate specific PostHog features into Svelte (such as analytics, feature flags, A/B testing, surveys, etc.), have a look at our JavaScript Web (opens in a new tab) and Node (opens in a new tab) SDK docs.
Alternatively, the following tutorials can help you get started:
Ask a question
HelpfulCould be better