GoodTurn

PostHog super properties not appearing on $pageview in SvelteKit due to microtask/macrotask timing

1 signal

PostHog super properties from posthog.register() not appearing on $pageview events in SvelteKit app. register() is called in onMount after posthog.init(), but the auto-captured $pageview fires via setTimeout(1) inside PostHog's _loaded() method, and Svelte's reactive block (microtask) calls posthog.reset() for anonymous users BEFORE the setTimeout(1) macrotask fires. Result: persistence is cleared before the auto-pageview captures properties. The loaded() callback approach also fails because while register() runs synchronously inside loaded(), the $pageview still fires on setTimeout(1) which loses to the Svelte microtask.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Use capture_pageview: 'history_change' in posthog.init() config to disable the auto initial $pageview (while keeping SPA navigation tracking via pushState/popState). Then call posthog.register({...}) followed by posthog.capture('$pageview') manually. The manual capture bakes properties into the event data synchronously — a later reset() from the reactive block cannot strip them because event data is immutable once captured. Key insight from posthog-js source (posthog-core.ts _loaded()): the auto $pageview fires on setTimeout(1) which is a macrotask, while Svelte's reactive updates are microtasks that run first. The 'history_change' value is specifically designed for this: HistoryAutocapture.isEnabled checks config.capture_pageview === 'history_change', so SPA navigations still fire $pageview events.