Files
supabase/packages/common/feature-flags.tsx
Pamela Chia 8c2d8d51ac feat(telemetry): stamp PostHog flags on tracked events (#53588)
Events sent through `sendTelemetryEvent` now include the app's loaded
PostHog flags as `$feature/<key>` properties, as `$pageview` already
does. The backend already adds these keys by evaluating flags remotely
for each event. The browser's values now take precedence over that
evaluation, so a follow-up can turn the per-event lookup off without
losing flag properties on events.

**Changed:**
- **Browser flag values on every tracked event**: `FeatureFlagProvider`
passes its PostHog flag map to the event builder each time flags load,
and the builder adds one `$feature/<key>` property per flag. A property
the caller sends under the same key wins.
- **Value source**: `$feature/*` on an event is now the value the app
rendered with. It follows the flag store, so for a moment after sign-in,
sign-out or an org or project switch it holds the previous values until
the refetch lands. The backend-computed `$active_feature_flags` is
unchanged and can differ from it in that window.
- **Logged-out docs, learn and ui-library events**: `$feature/*` now
holds the flag value the page was served. Until now the backend
evaluated it per visitor, so trends on those properties shift on each
app's deploy date.
- **Apps without PostHog flags**: www (`ph: false`) and kb (no provider)
keep an empty map, so their events get no new properties.

**Note:** I set the flags in the provider right before its state update
because an exposure event fired from a child effect, on the render where
its flag first resolves, must already see them. An effect in the
provider would run after that child effect. Events sent before the first
flag load still go out without browser flag values.

## To test

Tested on the PR preview:
- [x] Sign in to Studio and open the new project form. In the network
panel, find the `POST /platform/telemetry/event` request with action
`project_creation_default_privileges_exposed`: expect
`custom_properties` to include `$feature/dataApiRevokeOnCreateDefault`,
equal to `dataApiRevokeOnCreateDefaultEnabled`. Observed: both `false`,
response 201.
- [x] In Studio, after `GET /platform/telemetry/feature-flags` returns,
trigger any tracked event: expect its `custom_properties` to hold one
`$feature/<key>` entry per key in that response, with the same values.
Observed on `command_menu_opened` and the exposure event: every key in
the flags response present with the same value, no extra keys.
- [x] On the docs preview, trigger a tracked event after the flags
request returns: expect `$feature/<key>` entries matching the docs flags
response. Observed on `docs_search_v2_opened`: all keys match the
logged-out flags response.
- [x] On the www preview, trigger a tracked event: expect no
`$feature/*` keys in `custom_properties`. Observed on
`start_project_button_clicked`: `custom_properties` is
`{"buttonLocation":"Header Nav","platform":"www"}`, and www made no
feature-flags request.
## Linear
- fixes GROWTH-1395
2026-11-18 21:57:49 +09:00

345 lines
11 KiB
TypeScript

'use client'
import { components } from 'api-types'
import { FlagValues } from 'flags/react'
import {
createContext,
PropsWithChildren,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useAuth, useUser } from './auth'
import { getFlags as getDefaultConfigCatFlags } from './configcat'
import { hasConsented } from './consent-state'
import { get, post } from './fetchWrappers'
import { gotrueClient } from './gotrue'
import { ensurePlatformSuffix } from './helpers'
import { useParams } from './hooks'
import { setTelemetryFeatureFlags } from './telemetry-event'
type TrackFeatureFlagVariables = components['schemas']['TelemetryFeatureFlagBody']
export type CallFeatureFlagsResponse =
components['schemas']['TelemetryCallFeatureFlagsResponse_Output']
export async function getFeatureFlags(
API_URL: string,
options: { organizationSlug?: string; projectRef?: string } = {}
) {
try {
const url = new URL(`${ensurePlatformSuffix(API_URL)}/telemetry/feature-flags`)
if (options.organizationSlug) {
url.searchParams.set('organization_slug', options.organizationSlug)
}
if (options.projectRef) {
url.searchParams.set('project_ref', options.projectRef)
}
const data = await get(url.toString())
return data as CallFeatureFlagsResponse
} catch (error: any) {
if (error.message.includes('Failed to fetch')) {
console.error('Failed to fetch PH flags: API is not available')
}
throw error
}
}
export async function trackFeatureFlag(API_URL: string, body: TrackFeatureFlagVariables) {
const consent = hasConsented()
if (!consent) return undefined
await post(`${ensurePlatformSuffix(API_URL)}/telemetry/feature-flags/track`, { body })
}
export type FeatureFlagContextType = {
API_URL?: string
configcat: { [key: string]: boolean | number | string | null }
posthog: CallFeatureFlagsResponse
hasLoaded?: boolean
/**
* True when the flags were fetched for the signed-in user. Flags fetched logged out
* stay in the store after sign-in until the refetch lands.
*/
hasFlagsForSignedInUser?: boolean
/**
* True while ConfigCat flags are being re-evaluated after `getConfigCatFlags` changed,
* e.g. because its custom attributes changed. Until then, `configcat` holds values
* evaluated with the previous attributes.
*/
isConfigCatStale?: boolean
}
type ConfigCatFlagsFetcher = (
userEmail?: string
) => Promise<{ settingKey: string; settingValue: boolean | number | string | null | undefined }[]>
type FeatureFlagStore = FeatureFlagContextType & {
/** The `getConfigCatFlags` that produced the current ConfigCat values */
configCatFetcher?: ConfigCatFlagsFetcher
/** The user the flags were fetched for. Undefined when they were fetched logged out. */
userId?: string
}
export const FeatureFlagContext = createContext<FeatureFlagContextType>({
API_URL: undefined,
configcat: {},
posthog: {},
hasLoaded: false,
})
function getCookies() {
const pairs = document.cookie.split(';')
let cookies: Record<string, string> = {}
for (var i = 0; i < pairs.length; i++) {
var [t_key, value] = pairs[i].split('=')
const key = t_key.trim()
cookies[key] = unescape(value)
}
return cookies
}
export const FeatureFlagProvider = ({
API_URL,
enabled = true,
organizationSlug,
projectRef,
getConfigCatFlags,
children,
}: PropsWithChildren<{
API_URL?: string
/** Accepts either `boolean` which controls all feature flags or `{ cc: boolean, ph: boolean }` for individual providers */
enabled?: boolean | { cc: boolean; ph: boolean }
organizationSlug?: string
projectRef?: string
/** Custom fetcher for ConfigCat flags if passing in custom attributes */
getConfigCatFlags?: ConfigCatFlagsFetcher
}>) => {
const { isLoading } = useAuth()
const user = useUser()
const userEmail = user?.user_metadata?.email ?? user?.email
const params = useParams()
const resolvedOrganizationSlug = organizationSlug ?? params.slug
const resolvedProjectRef = projectRef ?? params.ref
const lastSentGroupContextRef = useRef<string | null>(null)
const [store, setStore] = useState<FeatureFlagStore>({
API_URL,
configcat: {},
posthog: {},
hasLoaded: false,
})
useEffect(() => {
let mounted = true
async function ensureGroupContext() {
if (!API_URL) return
const userId = user?.id
if (!userId) return
if (!hasConsented()) return
if (!resolvedOrganizationSlug && !resolvedProjectRef) return
const contextKey = [userId, resolvedOrganizationSlug ?? '', resolvedProjectRef ?? ''].join(
'|'
)
if (lastSentGroupContextRef.current === contextKey) return
try {
await post(
`${ensurePlatformSuffix(API_URL)}/telemetry/identify`,
{
user_id: userId,
...(resolvedOrganizationSlug && { organization_slug: resolvedOrganizationSlug }),
...(resolvedProjectRef && { project_ref: resolvedProjectRef }),
},
{ headers: { Version: '2' } }
)
lastSentGroupContextRef.current = contextKey
} catch {}
}
async function processFlags() {
if (!enabled || isLoading) return
const loadPHFlags =
(enabled === true || (typeof enabled === 'object' && enabled.ph)) && !!API_URL
const loadCCFlags = enabled === true || (typeof enabled === 'object' && enabled.cc)
let flagStore: FeatureFlagStore = {
configcat: {},
posthog: {},
configCatFetcher: getConfigCatFlags,
userId: user?.id,
}
// Run both async operations in parallel — allSettled so a failure in one doesn't block the other
const [phResult, ccResult] = await Promise.allSettled([
loadPHFlags
? (async () => {
await ensureGroupContext()
return getFeatureFlags(API_URL, {
organizationSlug: resolvedOrganizationSlug,
projectRef: resolvedProjectRef,
})
})()
: Promise.resolve({}),
loadCCFlags
? typeof getConfigCatFlags === 'function'
? getConfigCatFlags(userEmail)
: getDefaultConfigCatFlags(userEmail)
: Promise.resolve([]),
])
const flags = phResult.status === 'fulfilled' ? phResult.value : {}
if (phResult.status === 'rejected') {
console.warn('[FeatureFlags] PostHog flags failed', phResult.reason)
}
const flagValues = ccResult.status === 'fulfilled' ? ccResult.value : []
// Dev toolbar flag overrides are available in local dev and staging.
// Duplicated for tree-shaking — bundler must see literal process.env reference.
// Keep in sync: dev-tools/index.ts, DevToolbarContext.tsx, DevToolbar.tsx, DevToolbarTrigger.tsx
const env = process.env.NEXT_PUBLIC_ENVIRONMENT
const isDevToolsEnabled = env === 'local' || env === 'staging'
const safeParse = (value: string | undefined): Record<string, boolean | number | string> => {
if (!value) return {}
try {
return JSON.parse(value)
} catch {
return {}
}
}
// Process PostHog flags if loaded
if (Object.keys(flags).length > 0) {
// Apply dev toolbar overrides for PostHog flags
if (isDevToolsEnabled) {
try {
const cookies = getCookies()
const phOverrides = safeParse(cookies['x-ph-flag-overrides'])
flagStore.posthog = { ...flags, ...phOverrides }
} catch {
flagStore.posthog = flags
}
} else {
flagStore.posthog = flags
}
}
// Process ConfigCat flags if loaded
if (flagValues.length > 0) {
let overridesCookieValue: Record<string, boolean | number | string> = {}
try {
const cookies = getCookies()
// Merge overrides: vercel-flag-overrides first, then x-cc-flag-overrides (dev toolbar only)
// x-cc-flag-overrides takes precedence when dev tools are enabled
const vercelOverrides = safeParse(cookies['vercel-flag-overrides'])
const ccOverrides = isDevToolsEnabled ? safeParse(cookies['x-cc-flag-overrides']) : {}
overridesCookieValue = {
...vercelOverrides,
...ccOverrides, // local overrides take precedence
}
} catch {}
flagValues.forEach((item) => {
flagStore['configcat'][item.settingKey] =
overridesCookieValue[item.settingKey] ??
(item.settingValue === null ? null : (item.settingValue ?? false))
})
}
flagStore.hasLoaded = true
if (mounted) {
// Before setStore: a child effect that sends an event on the re-render must already see these flags
setTelemetryFeatureFlags(flagStore.posthog)
setStore(flagStore)
}
}
// [Joshen] getFlags get triggered everytime the tab refocuses but this should be okay
// as per https://configcat.com/docs/sdk-reference/js/#polling-modes:
// The polling downloads the config.json at the set interval and are stored in the internal cache
// which subsequently all getValueAsync() calls are served from there
processFlags()
// The flags endpoint refuses the pre-MFA token of a user with MFA enabled
const { data: auth } = gotrueClient.onAuthStateChange((event) => {
if (event === 'MFA_CHALLENGE_VERIFIED') processFlags()
})
return () => {
mounted = false
auth.subscription.unsubscribe()
}
}, [
enabled,
isLoading,
userEmail,
API_URL,
user?.id,
resolvedOrganizationSlug,
resolvedProjectRef,
getConfigCatFlags,
])
// Memoized so consumers only re-render when the flags or their staleness change
const contextValue = useMemo<FeatureFlagContextType>(() => {
const { configCatFetcher, userId, ...flags } = store
return {
...flags,
isConfigCatStale: configCatFetcher !== getConfigCatFlags,
hasFlagsForSignedInUser: !!user?.id && userId === user.id,
}
}, [store, getConfigCatFlags, user?.id])
return (
<FeatureFlagContext.Provider value={contextValue}>
{/*
[Joshen] Just support configcat flags in Vercel flags for now for simplicity
although I think it should be fairly simply to support PH too
*/}
<FlagValues values={store.configcat} />
{children}
</FeatureFlagContext.Provider>
)
}
export const useFeatureFlags = () => {
return useContext(FeatureFlagContext)
}
const isObjectEmpty = (obj: Object) => {
return Object.keys(obj).length === 0
}
export function useFlag<T = boolean>(name: string) {
const flagStore = useFeatureFlags()
const store = flagStore.configcat
// Flag store is empty means config cat is not loaded yet, return false
if (isObjectEmpty(store)) {
return false
}
if (store[name] === undefined) {
console.error(`Flag key "${name}" does not exist in ConfigCat flag store`)
return false
}
return store[name] as T
}