The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Fix first-touch referrer for initial $pageview (#41447)
Sean Oliverde8e9f6b1b6b
diff --git a/packages/common/hooks/useTelemetryCookie.tsx b/packages/common/hooks/useTelemetryCookie.tsxindex 25fa2b73f82..f6c563a2ed7 100644--- a/packages/common/hooks/useTelemetryCookie.tsx+++ b/packages/common/hooks/useTelemetryCookie.tsx@@ -1,43 +1,36 @@-// hooks/useTelemetryCookie.ts-import { useRouter } from 'next/compat/router'import { useEffect } from 'react'-import { IS_PROD, LOCAL_STORAGE_KEYS } from '../constants'-import { getSharedTelemetryData } from '../telemetry-utils'+import { LOCAL_STORAGE_KEYS } from '../constants'+import { getSharedTelemetryData, getTelemetryCookieOptions } from '../telemetry-utils'interface UseTelemetryCookieProps {- hasAcceptedConsent: boolean- title: string- referrer: string+ enabled: boolean}/**- * This hook saves the telemetry data to a cookie. The cookie will be sent when the user consents to telemetry. If they- * don't consent, the cookie will never be sent.+ * This hook saves the initial telemetry data to a cookie so we can preserve first-touch attribution+ * (e.g. `document.referrer`) until the initial pageview is emitted. If the user never+ * consents, this cookie is never used.*/-export function useTelemetryCookie({- hasAcceptedConsent,- title,- referrer,-}: UseTelemetryCookieProps) {- const router = useRouter()+export function useTelemetryCookie({ enabled }: UseTelemetryCookieProps) {const telemetryStorageKey = LOCAL_STORAGE_KEYS.TELEMETRY_DATAuseEffect(() => {- if (!router?.isReady) return+ if (typeof window === 'undefined') return+ if (!enabled) returnconst cookies = document.cookie.split(';')- const cookieOptions = IS_PROD ? 'path=/; domain=supabase.com' : 'path=/'+ const cookieOptions = getTelemetryCookieOptions()- const telemetryCookie = cookies.find((cookie) => cookie.trim().startsWith(telemetryStorageKey))+ const telemetryCookie = cookies.find((cookie) =>+ cookie.trim().startsWith(`${telemetryStorageKey}=`)+ )if (telemetryCookie) return- const telemetryData = getSharedTelemetryData(router.pathname)+ const telemetryData = getSharedTelemetryData(window.location.pathname)- if (!hasAcceptedConsent) {- const encodedData = encodeURIComponent(JSON.stringify(telemetryData))- document.cookie = `${telemetryStorageKey}=${encodedData}; ${cookieOptions}`- }- }, [hasAcceptedConsent, router?.isReady, telemetryStorageKey, title, router?.pathname, referrer])+ const encodedData = encodeURIComponent(JSON.stringify(telemetryData))+ document.cookie = `${telemetryStorageKey}=${encodedData}; ${cookieOptions}`+ }, [enabled, telemetryStorageKey])}export default useTelemetryCookiediff --git a/packages/common/index.tsx b/packages/common/index.tsxindex eccb30018ae..87b60f4e6f9 100644--- a/packages/common/index.tsx+++ b/packages/common/index.tsx@@ -11,3 +11,4 @@ export * from './hooks'export * from './MetaFavicons/pages-router'export * from './Providers'export * from './telemetry'+export * from './telemetry-utils'diff --git a/packages/common/telemetry-utils.ts b/packages/common/telemetry-utils.tsindex a37b7c2a7a5..604d6da7572 100644--- a/packages/common/telemetry-utils.ts+++ b/packages/common/telemetry-utils.ts@@ -1,4 +1,20 @@import { isBrowser } from './helpers'+import { IS_PROD } from './constants'+import { LOCAL_STORAGE_KEYS } from './constants'++export function getTelemetryCookieOptions() {+ if (typeof window === 'undefined') return 'path=/; SameSite=Lax'+ if (!IS_PROD) return 'path=/; SameSite=Lax'++ const hostname = window.location.hostname+ const isSupabaseCom = hostname === 'supabase.com' || hostname.endsWith('.supabase.com')+ return isSupabaseCom ? 'path=/; domain=supabase.com; SameSite=Lax' : 'path=/; SameSite=Lax'+}++export function clearTelemetryDataCookie() {+ if (!isBrowser) return+ document.cookie = `${LOCAL_STORAGE_KEYS.TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; ${getTelemetryCookieOptions()}`+}// Parse session_id from PostHog cookie since SDK doesn't expose session ID// (needed to correlate client and server events)@@ -25,9 +41,20 @@ function getPostHogSessionId(): string | null {export function getSharedTelemetryData(pathname?: string) {const sessionId = getPostHogSessionId()+ const pageUrl = (() => {+ if (!isBrowser) return ''++ try {+ const url = new URL(window.location.href)+ url.hash = ''+ return url.href+ } catch {+ return window.location.href.split('#')[0]+ }+ })()return {- page_url: isBrowser ? window.location.href : '',+ page_url: pageUrl,page_title: isBrowser ? document?.title : '',pathname: pathname ? pathname : isBrowser ? window.location.pathname : '',session_id: sessionId,diff --git a/packages/common/telemetry.tsx b/packages/common/telemetry.tsxindex 7ca9f7ed8a3..ad6ded4dda4 100644--- a/packages/common/telemetry.tsx+++ b/packages/common/telemetry.tsx@@ -8,13 +8,17 @@ import { useCallback, useEffect, useRef } from 'react'import { useLatest } from 'react-use'import { useUser } from './auth'import { hasConsented } from './consent-state'-import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from './constants'+import { IS_PLATFORM, IS_PROD, LOCAL_STORAGE_KEYS } from './constants'import { useFeatureFlags } from './feature-flags'import { post } from './fetchWrappers'import { ensurePlatformSuffix, isBrowser } from './helpers'import { useParams, useTelemetryCookie } from './hooks'import { TelemetryEvent } from './telemetry-constants'-import { getSharedTelemetryData } from './telemetry-utils'+import {+ clearTelemetryDataCookie,+ getSharedTelemetryData,+ getTelemetryCookieOptions,+} from './telemetry-utils'import { posthogClient } from './posthog-client'export { posthogClient }@@ -43,6 +47,63 @@ export const TelemetryTagManager = () => {//---// PAGE TELEMETRY//---+type SharedTelemetryData = ReturnType<typeof getSharedTelemetryData>++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') }),+ }++ // Ad network click IDs (first-touch attribution)+ const clickIdProps = {+ ...(getParam('gclid') && { gclid: getParam('gclid') }), // Google Ads+ ...(getParam('gbraid') && { gbraid: getParam('gbraid') }), // Google Ads (iOS)+ ...(getParam('wbraid') && { wbraid: getParam('wbraid') }), // Google Ads (iOS)+ ...(getParam('msclkid') && { msclkid: getParam('msclkid') }), // Microsoft Ads (Bing)+ ...(getParam('fbclid') && { fbclid: getParam('fbclid') }), // Meta (Facebook/Instagram)+ ...(getParam('rdt_cid') && { rdt_cid: getParam('rdt_cid') }), // Reddit Ads+ ...(getParam('ttclid') && { ttclid: getParam('ttclid') }), // TikTok Ads+ ...(getParam('twclid') && { twclid: getParam('twclid') }), // X Ads (Twitter)+ ...(getParam('li_fat_id') && { li_fat_id: getParam('li_fat_id') }), // LinkedIn Ads+ }++ return {+ ...utmProps,+ ...clickIdProps,+ first_touch_url: url.href,+ first_touch_pathname: url.pathname,+ ...(url.search && { first_touch_search: url.search }),+ }+ } catch {+ return {}+ }+}++function isExternalReferrer(referrer: string) {+ try {+ const hostname = new URL(referrer).hostname+ return hostname !== 'supabase.com' && !hostname.endsWith('.supabase.com')+ } catch {+ return false+ }+}+function handlePageTelemetry(API_URL: string,pathname?: string,@@ -50,21 +111,54 @@ function handlePageTelemetry([key: string]: unknown},slug?: string,- ref?: string+ ref?: string,+ telemetryDataOverride?: SharedTelemetryData) {// Send to PostHog client-side (only in browser)if (typeof window !== 'undefined') {- const pageData = getSharedTelemetryData(pathname)+ const livePageData = getSharedTelemetryData(pathname)+ const liveReferrer = livePageData.ph.referrer+ const cookieReferrer = telemetryDataOverride?.ph?.referrer++ const shouldUseCookieReferrer = Boolean(+ cookieReferrer && isExternalReferrer(cookieReferrer) && !isExternalReferrer(liveReferrer)+ )++ const pageData = telemetryDataOverride+ ? {+ ...livePageData,+ ph: {+ ...livePageData.ph,+ referrer: shouldUseCookieReferrer ? cookieReferrer! : liveReferrer,+ },+ }+ : livePageData+ const firstTouchAttributionProps = telemetryDataOverride+ ? getFirstTouchAttributionProps(telemetryDataOverride)+ : {}++ const $referrer = pageData.ph.referrer+ const $referring_domain = (() => {+ if (!$referrer) return undefined+ try {+ return new URL($referrer).hostname+ } catch {+ return undefined+ }+ })()// Align frontend and backend session IDs for correlationif (pageData.session_id) {- document.cookie = `session_id=${pageData.session_id}; path=/; SameSite=Lax`+ document.cookie = `session_id=${pageData.session_id}; ${getTelemetryCookieOptions()}`}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 } : {}),@@ -129,9 +223,7 @@ export const PageTelemetry = ({const featureFlags = useFeatureFlags()- const title = typeof document !== 'undefined' ? document?.title : ''- const referrer = typeof document !== 'undefined' ? document?.referrer : ''- useTelemetryCookie({ hasAcceptedConsent, title, referrer })+ useTelemetryCookie({ enabled: enabled && IS_PLATFORM })const pathname =pagesPathname ?? appPathname ?? (isBrowser ? window.location.pathname : undefined)@@ -192,15 +284,31 @@ export const PageTelemetry = ({!hasSentInitialPageTelemetryRef.current) {const cookies = document.cookie.split(';')- const telemetryCookie = cookies.find((cookie) => cookie.trim().startsWith(TELEMETRY_DATA))- if (telemetryCookie) {+ const telemetryCookieValue = cookies+ .map((cookie) => cookie.trim())+ .find((cookie) => cookie.startsWith(`${TELEMETRY_DATA}=`))+ ?.slice(`${TELEMETRY_DATA}=`.length)++ if (telemetryCookieValue) {try {- const encodedData = telemetryCookie.split('=')[1]- handlePageTelemetry(API_URL, pathnameRef.current, featureFlagsRef.current, slug, ref)- // remove the telemetry cookie- document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`+ const telemetryData = JSON.parse(+ decodeURIComponent(telemetryCookieValue)+ ) as SharedTelemetryData+ handlePageTelemetry(+ API_URL,+ pathnameRef.current,+ featureFlagsRef.current,+ slug,+ ref,+ telemetryData+ )} catch (error) {- console.error('Invalid telemetry data:', error)+ if (!IS_PROD) {+ console.warn('Invalid telemetry cookie data:', error)+ }+ handlePageTelemetry(API_URL, pathnameRef.current, featureFlagsRef.current, slug, ref)+ } finally {+ clearTelemetryDataCookie()}} else {handlePageTelemetry(API_URL, pathnameRef.current, featureFlagsRef.current, slug, ref)diff --git a/packages/ui-patterns/src/consent.tsx b/packages/ui-patterns/src/consent.tsxindex 30079f08027..7e563ee3243 100644--- a/packages/ui-patterns/src/consent.tsx+++ b/packages/ui-patterns/src/consent.tsx@@ -1,14 +1,12 @@'use client'-import { consentState, isBrowser, LOCAL_STORAGE_KEYS } from 'common'+import { clearTelemetryDataCookie, consentState, isBrowser } from 'common'import { useCallback, useEffect, useRef } from 'react'import { toast } from 'sonner'import { cn } from 'ui'import { useSnapshot } from 'valtio'import { ConsentToast } from './ConsentToast'-const { TELEMETRY_DATA } = LOCAL_STORAGE_KEYS-export const useConsentToast = () => {const consentToastId = useRef<string | number>()const snap = useSnapshot(consentState)@@ -27,8 +25,7 @@ export const useConsentToast = () => {if (!isBrowser) returnsnap.denyAll()- // remove the telemetry cookie- document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`+ clearTelemetryDataCookie()if (consentToastId.current) {toast.dismiss(consentToastId.current)