Back
Utility New

PostHog

Server-side PostHog integration with feature flags. Initializes PostHog client, group identification, and provides feature flag helpers with cookie-based caching.

Code

Wire the server handle, extend App.Locals, initialize PostHog in the layout, and provide the features context. See the PostHog Feedback component for the feedback UI.

1. src/hooks.server.ts

import { handlePosthogClient } from "$lib/hooks/server/posthog"; import { sequence } from "@sveltejs/kit/hooks"; export const handle = sequence(handlePosthogClient /* other handles */);

2. src/app.d.ts

import type { PostHog } from "posthog-node"; declare global { namespace App { interface Locals { posthog: PostHog; featureFlags: Record; } } } export {};

3. +layout.ts

import { browser } from "$app/environment"; import posthog from "posthog-js"; import { env } from "$env/dynamic/public"; export async function load({ parent, locals }) { const data = await parent(); const merged = { ...data, user: locals.user, featureFlags: locals.featureFlags, }; if (browser) { posthog.init(env.PUBLIC_POSTHOG_KEY, { api_host: "https://eu.i.posthog.com", defaults: "2026-01-30", session_recording: { maskTextSelector: "*", }, }); posthog.group("company", merged.user.company.key); } return merged; }

4. +layout.svelte

Requirements

  • Set PUBLIC_POSTHOG_KEY
  • The example uses event.locals.user to set the group for the session.

Installation

pnpm dlx shadcn-svelte@next add https://components.deckweiss.at/r/posthog.json