Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix: resolve 50% session tracking discrepancy on root route (#37853)

Sean Oliver97d746b66540
diff --git a/packages/common/posthog-client.ts b/packages/common/posthog-client.ts
index 5e3fc98c46b..b27e104efa3 100644
--- a/packages/common/posthog-client.ts
+++ b/packages/common/posthog-client.ts
@@ -1,6 +1,10 @@
import posthog from 'posthog-js'
import { PostHogConfig } from 'posthog-js'
+// Limit the max number of queued events
+// (e.g. if a user navigates around a lot before accepting consent)
+const MAX_PENDING_EVENTS = 20
+
interface PostHogClientConfig {
apiKey?: string
apiHost?: string
@@ -10,7 +14,9 @@ class PostHogClient {
private initialized = false
private pendingGroups: Record<string, string> = {}
private pendingIdentification: { userId: string; properties?: Record<string, any> } | null = null
+ private pendingEvents: Array<{ event: string; properties: Record<string, any> }> = []
private config: PostHogClientConfig
+ private readonly maxPendingEvents = MAX_PENDING_EVENTS
constructor(config: PostHogClientConfig = {}) {
this.config = {
@@ -34,6 +40,10 @@ class PostHogClient {
capture_pageview: false, // We'll manually track pageviews
capture_pageleave: false, // We'll manually track page leaves
loaded: (posthog) => {
+ // Apply pending properties that were set before PostHog
+ // initialized due to poor connection or user not accepting
+ // consent right away
+
// Apply any pending groups
Object.entries(this.pendingGroups).forEach(([type, id]) => {
posthog.group(type, id)
@@ -42,9 +52,26 @@ class PostHogClient {
// Apply any pending identification
if (this.pendingIdentification) {
- posthog.identify(this.pendingIdentification.userId, this.pendingIdentification.properties)
+ try {
+ posthog.identify(
+ this.pendingIdentification.userId,
+ this.pendingIdentification.properties
+ )
+ } catch (error) {
+ console.error('PostHog identify failed:', error)
+ }
this.pendingIdentification = null
}
+
+ // Flush any pending events
+ this.pendingEvents.forEach(({ event, properties }) => {
+ try {
+ posthog.capture(event, properties, { transport: 'sendBeacon' })
+ } catch (error) {
+ console.error('PostHog capture failed:', error)
+ }
+ })
+ this.pendingEvents = []
},
}
@@ -53,21 +80,51 @@ class PostHogClient {
}
capturePageView(properties: Record<string, any>, hasConsent: boolean = true) {
- if (!hasConsent || !this.initialized) return
+ if (!hasConsent) return
- // Store groups from properties if present (for later group() calls)
- if (properties.$groups) {
- Object.entries(properties.$groups).forEach(([type, id]) => {
- if (id) posthog.group(type, id as string)
- })
+ if (!this.initialized) {
+ // Queue the event for when PostHog initializes (up to cap)
+ // (e.g. poor connection or user not accepting consent right away)
+ if (this.pendingEvents.length >= this.maxPendingEvents) {
+ this.pendingEvents.shift() // Remove oldest event
+ }
+ this.pendingEvents.push({ event: '$pageview', properties })
+ return
}
- posthog.capture('$pageview', properties)
+ try {
+ // Store groups from properties if present (for later group() calls)
+ if (properties.$groups) {
+ Object.entries(properties.$groups).forEach(([type, id]) => {
+ if (id) posthog.group(type, id as string)
+ })
+ }
+
+ posthog.capture('$pageview', properties, { transport: 'sendBeacon' })
+ } catch (error) {
+ console.error('PostHog pageview capture failed:', error)
+ }
}
capturePageLeave(properties: Record<string, any>, hasConsent: boolean = true) {
- if (!hasConsent || !this.initialized) return
- posthog.capture('$pageleave', properties)
+ if (!hasConsent) return
+
+ if (!this.initialized) {
+ // Queue the event for when PostHog initializes (up to cap)
+ // (e.g. poor connection or user not accepting consent right away)
+ if (this.pendingEvents.length >= this.maxPendingEvents) {
+ this.pendingEvents.shift() // Remove oldest event
+ }
+ this.pendingEvents.push({ event: '$pageleave', properties })
+ return
+ }
+
+ try {
+ // Use sendBeacon for page leave to survive tab close
+ posthog.capture('$pageleave', properties, { transport: 'sendBeacon' })
+ } catch (error) {
+ console.error('PostHog pageleave capture failed:', error)
+ }
}
identify(userId: string, properties?: Record<string, any>, hasConsent: boolean = true) {
@@ -79,7 +136,11 @@ class PostHogClient {
return
}
- posthog.identify(userId, properties)
+ try {
+ posthog.identify(userId, properties)
+ } catch (error) {
+ console.error('PostHog identify failed:', error)
+ }
}
}
diff --git a/packages/common/telemetry-utils.ts b/packages/common/telemetry-utils.ts
index 00e25e69671..a37b7c2a7a5 100644
--- a/packages/common/telemetry-utils.ts
+++ b/packages/common/telemetry-utils.ts
@@ -1,10 +1,36 @@
import { isBrowser } from './helpers'
+// Parse session_id from PostHog cookie since SDK doesn't expose session ID
+// (needed to correlate client and server events)
+function getPostHogSessionId(): string | null {
+ if (!isBrowser) return null
+
+ try {
+ // Parse PostHog cookie to extract session ID
+ const phCookies = document.cookie.split(';').find((cookie) => cookie.trim().startsWith('ph_'))
+
+ if (phCookies) {
+ const cookieValue = decodeURIComponent(phCookies.split('=')[1])
+ const phData = JSON.parse(cookieValue)
+ if (phData.$sesid && Array.isArray(phData.$sesid) && phData.$sesid[1]) {
+ return phData.$sesid[1]
+ }
+ }
+ } catch (error) {
+ console.warn('Could not extract PostHog session ID:', error)
+ }
+
+ return null
+}
+
export function getSharedTelemetryData(pathname?: string) {
+ const sessionId = getPostHogSessionId()
+
return {
page_url: isBrowser ? window.location.href : '',
page_title: isBrowser ? document?.title : '',
pathname: pathname ? pathname : isBrowser ? window.location.pathname : '',
+ session_id: sessionId,
ph: {
referrer: isBrowser ? document?.referrer : '',
language: navigator.language ?? 'en-US',
diff --git a/packages/common/telemetry.tsx b/packages/common/telemetry.tsx
index bc898094865..3eaf60dd394 100644
--- a/packages/common/telemetry.tsx
+++ b/packages/common/telemetry.tsx
@@ -54,6 +54,12 @@ export function handlePageTelemetry(
// Send to PostHog client-side (only in browser)
if (typeof window !== 'undefined') {
const pageData = getSharedTelemetryData(pathname)
+
+ // Align frontend and backend session IDs for correlation
+ if (pageData.session_id) {
+ document.cookie = `session_id=${pageData.session_id}; path=/; SameSite=Lax`
+ }
+
posthogClient.capturePageView({
$current_url: pageData.page_url,
$pathname: pageData.pathname,
@@ -63,6 +69,7 @@ export function handlePageTelemetry(
...(ref ? { project: ref } : {}),
},
page_title: pageData.page_title,
+ ...(pageData.session_id && { $session_id: pageData.session_id }),
...pageData.ph,
...Object.fromEntries(
Object.entries(featureFlags || {}).map(([k, v]) => [`$feature/${k}`, v])
@@ -72,12 +79,14 @@ export function handlePageTelemetry(
// Send to backend
// TODO: Remove this once migration to client-side page telemetry is complete
- return post(
- `${ensurePlatformSuffix(API_URL)}/telemetry/page`,
+ const sharedData = getSharedTelemetryData(pathname)
+ const { session_id, ...backendData } = sharedData // Remove session_id from backend payload (it's already in the cookie)
+
+ const payload =
telemetryDataOverride !== undefined
? { feature_flags: featureFlags, ...telemetryDataOverride }
: {
- ...getSharedTelemetryData(pathname),
+ ...backendData,
...(slug || ref
? {
groups: {
@@ -87,9 +96,10 @@ export function handlePageTelemetry(
}
: {}),
feature_flags: featureFlags,
- },
- { headers: { Version: '2' } }
- )
+ }
+ return post(`${ensurePlatformSuffix(API_URL)}/telemetry/page`, payload, {
+ headers: { Version: '2' },
+ })
}
export function handlePageLeaveTelemetry(
@@ -108,6 +118,7 @@ export function handlePageLeaveTelemetry(
$current_url: pageData.page_url,
$pathname: pageData.pathname,
page_title: pageData.page_title,
+ ...(pageData.session_id && { $session_id: pageData.session_id }),
})
}