Generated banner for Integration Sveltekit
Generated logo for Integration Sveltekit

Integration Sveltekit

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • No issues found

From the author

PostHog integration for SvelteKit applications
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive, step-by-step procedure for adding PostHog analytics to SvelteKit projects. It covers client-side initialization, server-side tracking, user identification, and error tracking. The workflow emphasizes best practices such as using environment variables, implementing reverse proxies to bypass ad blockers, and maintaining consistency with provided example patterns.

What it does

  • Guides users through a multi-step integration process for PostHog in SvelteKit.
  • Provides patterns for both client-side and server-side event tracking.
  • Includes instructions for user identification and error tracking implementation.
  • Details the configuration of reverse proxies to improve data reliability.
  • Requires the use of environment variables for secure credential management.
  • Mandates validation of Svelte components using provided tooling.

When to use it

  • When you need to add analytics to a new or existing SvelteKit application.
  • When you want to track user behavior across both client and server environments.
  • When you need to implement robust error tracking within a SvelteKit project.
  • When you are setting up session replay and require specific SvelteKit configuration adjustments.

Advantages

  • Ensures a consistent and reliable integration pattern.
  • Promotes secure handling of API keys via environment variables.
  • Addresses common SvelteKit-specific pitfalls like SSR compatibility.
  • Facilitates accurate user correlation between frontend and backend.

Usage examples

“How do I start integrating PostHog into my SvelteKit app?”
The agent initiates the workflow, starting with the 'PostHog Setup - Begin' phase to analyze your project structure and create an event tracking plan.
“How should I handle server-side tracking in SvelteKit?”
The agent directs you to use the singleton pattern in 'src/lib/server/posthog.ts' as shown in the reference example.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/posthog/integration-sveltekit/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip integration-sveltekit.zip -d .agents/skills

Documentation by PostHog

PostHog integration for SvelteKit

This skill helps you add PostHog analytics to SvelteKit applications.

Workflow

Follow these steps in order to complete the integration:

  1. basic-integration-1.0-begin.md - PostHog Setup - Begin ← Start here

  2. basic-integration-1.1-edit.md - PostHog Setup - Edit

  3. basic-integration-1.2-revise.md - PostHog Setup - Revise

  4. basic-integration-1.3-conclude.md - PostHog Setup - Conclusion

Reference files

  • references/EXAMPLE.md - SvelteKit example project code

  • references/svelte.md - Svelte - docs

  • references/identify-users.md - Identify users - docs

  • references/basic-integration-1.0-begin.md - PostHog setup - begin

  • references/basic-integration-1.1-edit.md - PostHog setup - edit

  • references/basic-integration-1.2-revise.md - PostHog setup - revise

  • references/basic-integration-1.3-conclude.md - PostHog setup - conclusion

The example project shows the target implementation pattern. Consult the documentation for API details.

Key principles

  • Environment variables: Always use environment variables for PostHog keys. Never hardcode them.

  • Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.

  • Match the example: Your implementation should follow the example project's patterns as closely as possible.

Framework guidelines

  • Set paths.relative to false in svelte.config.js — this is required for PostHog session replay to work correctly with SSR and is easy to miss

  • Use the Svelte MCP server tools to check Svelte documentation (list-sections, get-documentation) and validate components (svelte-autofixer) — always run svelte-autofixer on new or modified .svelte files before finishing

Identifying users

Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to maintain correlation.

Error tracking

Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries.

Files

references/svelte.md

Svelte - Docs

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 and Node.js SDKs.

Beta: integration via LLM

Install PostHog for Svelte in seconds with our wizard by running this prompt with LLM coding agents like Cursor and Bolt, or by running it in your terminal.

npx @posthog/wizard@latest

Learn more

Or, to integrate manually, continue with the rest of this guide.

Client-side setup

Install posthog-js using your package manager:

PostHog AI

npm
npm install --save posthog-js
Yarn
yarn add posthog-js
pnpm
pnpm add posthog-js
Bun
bun add posthog-js

Then, if you haven't created a root layout 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.

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

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, LLM traces, and error tracking to the same person — and lets backend events link back too.

See our guide on identifying users 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.

Set up a reverse proxy (recommended)

We recommend setting up a reverse proxy, so that events are less likely to be intercepted by tracking blockers.

We have our own managed reverse proxy service, 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, AWS Cloudfront, and Vercel.

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.

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, 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).

Server-side setup

Install posthog-node using your package manager:

PostHog AI

npm
npm install posthog-node --save
Yarn
yarn add posthog-node
pnpm
pnpm add posthog-node
Bun
bun add posthog-node

Then, initialize the PostHog Node client where you'd like to use it on the server side. For example, in a load function:

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.

Feature flags

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 and Node docs for more details.

Configuring session replay for server-side rendered apps

By default, Svelte uses relative asset paths 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,
     },
 },

Next steps

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 and Node SDK docs.

Alternatively, the following tutorials can help you get started:

Community questions

Ask a question

Was this page useful?

HelpfulCould be better

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/posthog/integration/skills/sveltekit · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
PostHog/skills

AutoGineer is not affiliated with or endorsed by PostHog or PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download integration-sveltekit.zip