Files
supabase/packages/common/page-telemetry.ts
Pamela Chia 62d6bf56f8 fix(telemetry): send the live posthog session id on custom events (#53504)
Custom events sent through the telemetry endpoint often carry a session
id the browser's PostHog session has already left: 8.9% of
server-captured events in a recent week had an id more than 24 hours
old, against 0.046% of browser-captured ones. Two things on the client
cause it. The `session_id` in the request body is parsed out of the
PostHog cookie without going through posthog-js, so a custom event never
rotates an expired session. And the `session_id` cookie, which the API
reads for the events it emits itself, was written on each pageview
before posthog-js rotated the session, so the first pageview after an
idle period stored the previous session's id.

**Changed:**
- **Custom events carry the live session id**: I changed
`buildTelemetryEventRequest` to ask posthog-js for the session id the
way a captured event does, so an expired session rotates first. Until
posthog-js has loaded it sends the cookie-parsed id, as before.
- **The `session_id` cookie follows the session**: I moved the write
from the pageview handler to posthog-js's session-change callback, plus
one write when posthog-js loads, so the cookie changes when the session
does.
- **The cookie stays cleared after an opt-out**: when a visitor
withdraws consent, posthog-js resets the session, and the new id would
have been written back over the cleared cookie. I skip the write once
the visitor has opted out, in this tab or another. Unit tests cover this
one: preview builds accept consent by default, so withdrawal can't be
exercised there.
- **Session metrics will step**: custom events now count as session
activity. A long-lived tab that sends events without navigating stays in
one session, so expect fewer, longer sessions from the day this reaches
each app.

**Note:** The API starts reading the body's `session_id` in a companion
change on its side. Either can deploy first: the field is already sent
today and ignored.

## To test

Tested on the PR preview:
- [x] In Studio with the Network tab open, open the user dropdown in the
header. Expect the `telemetry/event` request body's `session_id` to
equal the `session_id` cookie.
- [x] Open the dropdown again right away. Expect the same `session_id`
as in the first request.
- [x] Leave that tab untouched for 35 minutes, then open the user
dropdown again without navigating. Expect a different `session_id` in
the request body than in the first step, and the `session_id` cookie to
equal the new one. Observed after 38 idle minutes.
- [x] Navigate to another Studio page. Expect the `session_id` cookie to
keep the value from the previous step. Observed on an in-app navigation
to the account page.

## Linear
- fixes GROWTH-1509
2026-11-20 16:22:11 +09:00

212 lines
6.5 KiB
TypeScript

import type { FirstReferrerData, MwDiagData } from './first-referrer-cookie'
import { isExternalReferrer, isOAuthRedirectReferrer } from './first-referrer-cookie'
import { posthogClient } from './posthog-client'
import type { SharedTelemetryData } from './telemetry-first-touch-store'
import { getSharedTelemetryData } from './telemetry-utils'
export const FIRST_TOUCH_CLICK_ID_KEYS = [
'gclid', // Google Ads
'gbraid', // Google Ads (iOS)
'wbraid', // Google Ads (iOS)
'msclkid', // Microsoft Ads (Bing)
'fbclid', // Meta (Facebook/Instagram)
'rdt_cid', // Reddit Ads
'ttclid', // TikTok Ads
'twclid', // X Ads (Twitter)
'li_fat_id', // LinkedIn Ads
'bfcid', // Freebuff Ads
'oppref', // ChatGPT Ads (OpenAI)
] as const
export function getFirstTouchAttributionProps(telemetryData: SharedTelemetryData) {
const urlString = telemetryData.page_url
try {
const url = new URL(urlString)
url.hash = ''
const params = url.searchParams
const getParam = (key: string) => {
const value = params.get(key)
return value && value.length > 0 ? value : undefined
}
const utmProps = {
...(getParam('utm_source') && { $utm_source: getParam('utm_source') }),
...(getParam('utm_medium') && { $utm_medium: getParam('utm_medium') }),
...(getParam('utm_campaign') && { $utm_campaign: getParam('utm_campaign') }),
...(getParam('utm_content') && { $utm_content: getParam('utm_content') }),
...(getParam('utm_term') && { $utm_term: getParam('utm_term') }),
}
const clickIdProps = Object.fromEntries(
FIRST_TOUCH_CLICK_ID_KEYS.flatMap((key) => {
const value = getParam(key)
return value ? [[key, value]] : []
})
)
return {
...utmProps,
...clickIdProps,
first_touch_url: url.href,
first_touch_pathname: url.pathname,
...(url.search && { first_touch_search: url.search }),
}
} catch {
return {}
}
}
interface HandlePageTelemetryOptions {
apiUrl: string
pathname?: string
featureFlags?: Record<string, unknown>
slug?: string
ref?: string
telemetryDataOverride?: SharedTelemetryData
firstReferrerData?: FirstReferrerData | null
mwDiagData?: MwDiagData | null
}
export function handlePageTelemetry({
pathname,
featureFlags,
slug,
ref,
telemetryDataOverride,
firstReferrerData,
mwDiagData,
}: HandlePageTelemetryOptions) {
if (typeof window !== 'undefined') {
const livePageData = getSharedTelemetryData(pathname)
const liveReferrer = livePageData.ph.referrer
const storedReferrer = telemetryDataOverride?.ph?.referrer
const shouldUseStoredReferrer = Boolean(
storedReferrer &&
isExternalReferrer(storedReferrer) &&
!isOAuthRedirectReferrer(storedReferrer) &&
(!isExternalReferrer(liveReferrer) || isOAuthRedirectReferrer(liveReferrer))
)
const pageData = telemetryDataOverride
? {
...livePageData,
ph: {
...livePageData.ph,
referrer: shouldUseStoredReferrer ? storedReferrer! : liveReferrer,
},
}
: { ...livePageData, ph: { ...livePageData.ph } }
const firstTouchAttributionProps: Record<string, string> = {
...(telemetryDataOverride ? getFirstTouchAttributionProps(telemetryDataOverride) : {}),
}
const firstReferrerCookiePresent = Boolean(firstReferrerData)
let firstReferrerCookieConsumed = false
if (
firstReferrerData &&
isExternalReferrer(firstReferrerData.referrer) &&
!isOAuthRedirectReferrer(firstReferrerData.referrer) &&
(!isExternalReferrer(pageData.ph.referrer) || isOAuthRedirectReferrer(pageData.ph.referrer))
) {
pageData.ph.referrer = firstReferrerData.referrer
firstReferrerCookieConsumed = true
const { utms, click_ids, landing_url, ts } = firstReferrerData
Object.entries(utms).forEach(([key, value]) => {
const phKey = key.startsWith('utm_') ? `$${key}` : key
firstTouchAttributionProps[phKey] = value
})
Object.entries(click_ids).forEach(([key, value]) => {
firstTouchAttributionProps[key] = value
})
try {
const url = new URL(landing_url)
firstTouchAttributionProps.first_touch_url = url.href
firstTouchAttributionProps.first_touch_pathname = url.pathname
if (url.search) {
firstTouchAttributionProps.first_touch_search = url.search
} else {
delete firstTouchAttributionProps.first_touch_search
}
} catch {
// Skip if landing URL is malformed
}
if (ts !== undefined) {
firstTouchAttributionProps.first_touch_timestamp = new Date(ts).toISOString()
}
}
const $referrer = pageData.ph.referrer
const $referring_domain = (() => {
if (!$referrer) return undefined
try {
return new URL($referrer).hostname
} catch {
return undefined
}
})()
posthogClient.capturePageView({
$current_url: pageData.page_url,
$pathname: pageData.pathname,
$host: new URL(pageData.page_url).hostname,
...($referrer && { $referrer }),
...($referring_domain && { $referring_domain }),
...firstTouchAttributionProps,
$groups: {
...(slug ? { organization: slug } : {}),
...(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])
),
// Only included on the initial pageview — subsequent pageviews omit firstReferrerData entirely
...(firstReferrerData !== undefined && {
first_referrer_cookie_present: firstReferrerCookiePresent,
first_referrer_cookie_consumed: firstReferrerCookieConsumed,
}),
...(mwDiagData && {
mw_diag_hit: mwDiagData.hit,
mw_diag_would_stamp: mwDiagData.would_stamp,
mw_diag_has_existing_cookie: mwDiagData.has_existing_cookie,
}),
})
}
return Promise.resolve()
}
export function handlePageLeaveTelemetry(
_API_URL: string,
pathname: string,
_featureFlags?: {
[key: string]: unknown
},
_slug?: string,
_ref?: string
) {
if (typeof window !== 'undefined') {
const pageData = getSharedTelemetryData(pathname)
posthogClient.capturePageLeave({
$current_url: pageData.page_url,
$pathname: pageData.pathname,
page_title: pageData.page_title,
...(pageData.session_id && { $session_id: pageData.session_id }),
})
}
return Promise.resolve()
}