telemetry-standards
PostHog ईवेंट ट्रैकिंग मानक Supabase Studio के लिए। समीक्षा करते समय उपयोग करें।
npx skills add https://github.com/supabase/supabase --skill telemetry-standardsTelemetry Standards for Supabase Studio
Standards for PostHog event tracking in apps/studio/. Apply these when
reviewing PRs that touch tracking or when implementing new tracking.
Event Naming
Format: [object]_[verb] in snake_case
Approved verbs only: opened, clicked, submitted, created, removed, updated, evaluated, added, enabled, disabled, copied, exposed, failed, closed, completed, applied
This list is the authority. packages/common/telemetry-constants.ts still holds older events with other verbs, so don't take a verb from an existing event.
created is for a new named resource, added for content put into an existing one. evaluated is for a decision the system made, not a user action.
clicked and submitted name the user's action and fire in its handler. The other verbs name a result and fire once it has happened. A call in a submit or confirm handler that runs before the request resolves counts attempts, failed ones included, so name that event submitted. To use a result verb (updated, removed, enabled), move the call to where the request has succeeded (Mutation outcomes under Required Pattern).
Flag these:
- Unapproved verbs (saved, viewed, seen, pressed, etc.)
- Wrong order:
click_product_card→ should beproduct_card_clicked - Wrong casing:
productCardClicked→ should beproduct_card_clicked
Good examples:
product_card_clickedbackup_button_clickedsql_query_submitted
Common mistakes with corrections:
database_saved→save_button_clickedordatabase_updated(unapproved verb)snippet_moved→snippet_folder_updated(unapproved verb: a move updates where the item lives)click_backup_button→backup_button_clicked(wrong order)dashboardViewed→ don't track passive views on page loadcomponent_rendered→ don't track — no user interaction
Property Standards
Casing: camelCase preferred for new events. The codebase has existing snake_case properties (e.g., schema_name, table_name) — when adding properties to an existing event, match its established casing. Match casing only: don't copy these properties into new events, because they carry user-defined names (see Privacy).
Names must be self-explanatory:
{ productType: 'database', planTier: 'pro' }{ assistantType: 'sql', suggestionType: 'optimization' }
Flag these:
- Generic names:
label,value,name,data - PascalCase properties
- Inconsistent names across similar events (e.g.,
assistantTypein one event,aiTypein a related event) - Mixing camelCase and snake_case within the same event
- A name another event already sends with a different type. PostHog keeps one type per property name across the whole project, so values of another type can read as empty in insights. Generic names (
step,type,status,count) collide most: searchpackages/common/telemetry-constants.tsfor the name first
What NOT to Track
- Passive views/renders on page load (
dashboard_viewed,sidebar_appeared,page_loaded) - Component appearances without user interaction
- Generic "viewed" or "seen" events — already captured by pageview events
DO track: user clicks, form submissions, explicit opens/closes, user-initiated actions.
Exception: _exposed events for A/B experiment exposure tracking are valid even though they fire on render.
Privacy: User-Defined Names and Identifiers
Never track PII (emails, names, IPs, etc.) in event properties.
Event properties must also never contain anything a user chose or typed for their own project. These are customer data even though they are not PII, and sending them is outside our privacy policy. Mask or omit:
- Schema, table, column, function, bucket, policy, project and branch names
- Any other user-defined name or label (index, trigger, role, extension setting, edge function, secret key, and so on)
- SQL text, filters, search terms, file or object paths, and other free-text input
- Row, object or record IDs, and any ID or ref not already attached by
useTrack - Raw error messages or stack traces, which often quote schema, table or column names. Send an error code or category instead
useTrack attaches groups.project (project ref) and groups.organization (org slug) whenever a project or org is selected. Don't add these, or other IDs, as properties. To attribute an event to a different project or org (one that was just created, for example), pass it as the third argument to track().
Send a count, enum, boolean or action category instead of the raw value. Type new properties as string-literal unions or boolean/number rather than plain string, so a raw name is harder to pass by accident. Feature flag values are a separate case and follow the feature flag section below.
// Don't (illustrative): raw names identify the customer's data model
track('table_copied', { schemaName: 'billing_internal', tableName: 'invoices' })
// Do (illustrative): categories, counts and booleans carry the same product insight
track('database_schema_visualizer_copied', { content: 'table_sql' })
track('database_schema_selector_updated', { schemaType: 'custom' }) // 'public' | 'protected' | 'custom'
track('policy_created', { operation: 'select', hasCheckExpression: true })
If you need to tell values apart, derive a category (public / protected / custom), a count (tableCount), or a boolean (isDefaultSchema). If a raw name seems essential, stop and ask before adding it.
This section takes precedence over "match similar events" guidance elsewhere in this skill: if a similar event carries a user-defined name, don't copy that property.
Privacy: Secrets, Project Content and URL State
Telemetry only runs for visitors who accepted analytics. Consent does not make it acceptable to collect secrets or the data customers keep in their projects.
Also never send, in any property:
- Secrets: API keys, JWTs, access or refresh tokens, passwords, connection strings, invite or OAuth codes. Pasted input often contains them
- Content read from a project: row values, log lines, query results, AI responses
- Ids of a customer's end users, and phone numbers
Helpers that send the shape instead of the text:
- Search input:
describeSearchQueryinpackages/common/search-query-telemetry.ts - Errors:
useTrackFunnelErrorinapps/studio/lib/telemetry/use-track-funnel-error.ts, which only accepts a classified reason fromfunnel-errors.ts
The page URL goes out with every event. Pageviews and custom events carry the current URL and the referrer automatically, so URL state is telemetry:
- Do not put tokens, user input or row values in the URL path, query string, or hash of a route
redactUrlKeywords()inpackages/common/telemetry-utils.tsalready strips all URL hashes and redacts all query parameter values outsideREADABLE_URL_PARAMS— never add sensitive query keys toREADABLE_URL_PARAMS, and add redaction + a test inpackages/common/telemetry-utils.tsin the same PR if a route puts sensitive data in a URL path segment
Consent and Transport
- Send events only through
useTrack(Studio) or the app'suseSendTelemetryEvent, and pageviews throughPageTelemetry. They check consent. Never importposthog-jsoutsidepackages/common/posthog-client.tsor post to an analytics endpoint directly - Don't add a direct
sendTelemetryEventcall in Studio.useStudioCommandMenuTelemetryis the one caller besidesuseTrack: it forwards events the shared command menu has already built - Always pass the real consent state to
posthogClientmethods. Never rely on a parameter default - Do not write analytics cookies or storage (ids, attribution, experiment assignment) before the visitor accepts. Anything stored after consent must be cleared in
revokeTrackingConsent(packages/common/consent-state.ts) when consent is withdrawn - A new third-party script, pixel or embed that receives visitor data needs a consent gate and a Legal review before it merges. Ask @supabase/growth-eng to route it
- Nothing may be sent when
IS_PLATFORMis false. Self-hosted Studio sends no telemetry
Required Pattern
Never use data-attr (or any other data-* attribute) to send PostHog events. Track every event with an explicit track() call from useTrack, defined in packages/common/telemetry-constants.ts. PostHog autocapture is off (autocapture: false in packages/common/posthog-client.ts), so a data-attr sends nothing, and it bypasses event typing and the review rules in this skill. A click you want measured gets a track() call. Don't add new data-attr attributes, and replace existing ones with track() when touching that code. Any that remain must keep a static string value, never built from user-defined names, in case autocapture is enabled later.
Import useTrack from @/lib/telemetry/track (within apps/studio/).
import { useTrack } from '@/lib/telemetry/track'
const MyComponent = () => {
const track = useTrack()
const handleClick = () => {
track('product_card_clicked', {
productType: 'database',
planTier: 'pro',
source: 'dashboard',
})
}
return <button onClick={handleClick}>Click me</button>
}
Where the track() call goes:
- Mutation outcomes. Don't track in the callbacks passed as the second argument to
mutate()(onSuccess,onError): they are skipped if the component unmounts first. Track aroundawait mutateAsync()(after it for success, in acatchfor failure), or in the callbacks passed to the mutation hook itself (useXMutation({ onSuccess, onError })) when the hook always calls them: some return early, on a 202 for example. The selected project can change before the response arrives, so attribute the event to the mutation's own project or org (from its variables, or from the response for a create) with the thirdtrack()argument, for example{ project: variables.projectRef }. - One meaning per event. When one event name fires from several places, every call site fires on the same kind of user action, so the counts are comparable. Don't mix a
copyevent handler on a DOM element, which also fires on keyboard and partial-selection copies, with a Copy button's click callback under one event name: track the same action in both, or add a property that tells them apart. - Submitted values. Capture what the user submitted at submit time, not in the success callback. A form can stay editable while the request is in flight, so reading it on success can report a value that was not the one sent.
- Result counts. A count of what a search or filter returned comes from the query or list the page already renders: its shared query options, or the filtered array. Don't copy the query key, fetcher or filter predicate into the tracking code. A copy drifts from the list as soon as one of them changes, and the event then reports a count the user never saw.
- Dismiss and abandonment events. Every property must be able to take a different value at that call site. Read it from state that exists while the user is still in the flow, not from a result that is only set after success: otherwise every abandonment reports the same value. The success path (a Done button, for example) must not go through the dismiss handler, or each success also counts as an abandonment.
- Conditionally rendered elements. A
track()call on an element that renders only for some items (a link rendered only when the item has anhref, for example) never fires for the others, and they read as zero. Track the same action on whatever the other items render in its place (a button instead of the link, for example). Don't move the call to a wider element such as the row: that counts clicks that were not on the link. - Values that are never sent. Each value in a property's union must be sent by some call site. Check the early returns above the
track()call: a branch that returns first (a choice that only takes effect after a second step, for example) never sends its value, and it reads as zero. Track that value where the action completes. Leave out a property that can only take one value until a second exists. - Components rendered in several places. A property value that names where the action happened (
source: 'project_home', for example) must be true at every place the component renders. Before hardcoding a page name, find every render site: a layout can render the component on pages you did not open. When it renders on more than one page, take the value from a prop each render site passes, or name the value after the component. The same check applies to anything the tracking reads: at a render site with no org or project selected, a call that needs the slug fails, or reports filters that were never applied. Pass the value in from that render site, or skip the tracking there and leave that page out of@page. - Debounced or delayed sends.
useTrackreads the project, org and pathname when the event is sent, not when the user acted. An event sent from a debounce or timer that outlives a navigation is attributed to the destination page. Send on the action where possible. When the send has to wait, the third argument can pin the project or org, but the page cannot be overridden. - Events sent just before leaving the page. A request started right before a full-page navigation (an external link, an OAuth redirect) can be canceled. Add the event's action to
KEEPALIVE_ACTIONSinpackages/common/telemetry-event.ts. Never turn keepalive on for every event: the browser's in-flight keepalive budget is small and shared, so other events would be dropped. - Actions that change nothing. An event named for a result (
closed,removed,updated) fires only when the handler changed something. Bulk and menu actions can run on nothing: Close Others with one tab open, a move into the folder the items are already in, a sort set to its current value. Guard thetrack()call on the items that will change, not on the click. A count property reports the items that changed, not the items selected. - Unresolved or failed async queries. Don't compute event properties from React Query data that hasn't succeeded yet (e.g.
githubConnection ? 1 : 0) — clicks while pending or after an error misreport unknown states as0/false. RequireisSuccess(not merely settled /!isPending, since an errored query has settled whiledatais stillundefined) or omit the property when data is unavailable. - Duplicated handlers & analytical purpose. Audit literal
track()properties after copying a mutation handler (e.g. classic vs scoped tokens). Add telemetry only when it answers a concrete product or rollout question — skip routine preference toggles unless you plan to measure them.
Feature Flag Measurement
A feature flag that gates behavior needs telemetry on both the flag state and how users respond to the new behavior (toggle clicks, opt-in actions), so the rollout can be measured.
- PostHog flags (
usePHFlag, or PostHog-backed hooks such asuseDataApiRevokeOnCreateDefaultEnabled): capture the flag value in a relevanttrack()call. - ConfigCat flags (
useFlagfromcommon) are a different system — this pattern does not apply to them.
usePHFlag returns undefined while the PostHog store is still loading. Read the raw flag via usePHFlag('flagName'), not through wrapper hooks that coerce undefined to false, and use a conditional spread so the property is omitted (not false) until the flag has resolved:
As always, track() runs inside the user-action handler — never in the component body or an effect (experiment _exposed events excepted, see What NOT to Track):
const track = useTrack()
const flagValue = usePHFlag<boolean>('myBooleanFlag') // for boolean flags
const handleSubmit = () => {
track('event_name', {
...(flagValue !== undefined && { myFlagEnabled: flagValue }),
})
}
Experiment exposure. Send <experiment_id>_experiment_exposed through useTrack with the variant, once per mount, and only once flags have loaded for the signed-in user (hasFlagsForSignedInUser from useFeatureFlags() in packages/common/feature-flags.tsx): the value held before that belongs to the logged-out visitor.
For string-valued flags (e.g. experiment variants), use usePHFlag<string>('flagName'); a flag that may be migrated from boolean to multivariate is typed usePHFlag<boolean | string>. ProjectCreationForm.tsx (dataApiRevokeOnCreateDefault) is the canonical example.
Event Definitions
All events must be defined as TypeScript interfaces in packages/common/telemetry-constants.ts:
/**
* [Event description]
*
* @group Events
* @source [what triggers this event]
*/
export interface MyFeatureClickedEvent {
action: 'my_feature_clicked'
properties: {
/** Description of property */
featureType: 'basic' | 'advanced'
}
groups: TelemetryGroups
}
Add the new interface to the TelemetryEvent union type so useTrack picks it up.
@group Events and @source are required on every event; add @page when the event fires from a specific page. All three must be accurate.
An event fired from an organization-level page (/org/{slug}/...) gets its own event name and groups: Omit<TelemetryGroups, 'project'> (see organization_mfa_enforcement_updated). Don't reuse a project-scoped event there: no project is selected, so useTrack sends it without the project group and the type does not catch it.
Review Rules
When reviewing a PR, flag a break of any of these as a required change, even when the value looks harmless:
- Naming: Event Naming
- Properties: Property Standards. Search
packages/common/telemetry-constants.tsfor similar events and check that property names match - Passive view tracking: What NOT to Track
- Inaccurate docs:
@sourceor@pagethat doesn't match the implementation (Event Definitions) - Feature flags and experiment exposure: Feature Flag Measurement
- User-defined names or identifiers in properties: Privacy: User-Defined Names and Identifiers
- Secrets, project content, URL state or consent: Privacy: Secrets, Project Content and URL State and Consent and Transport
- Tracking placement: the placement rules under Required Pattern, including no new
data-attror otherdata-*attribute used for tracking - Org-level events: a project-scoped event reused on an organization-level page (Event Definitions)
When a PR adds a meaningful new user-facing flow or action (such as a feature CTA, form submission, or rollout-gated control) without tracking — skip routine preference toggles unless they answer a concrete analytical question — suggest:
- "This adds a user interaction that may benefit from tracking."
- Propose the event name following
[object]_[verb]convention - Propose the
useTrack()call with suggested properties
Well-Formed Event Examples
From the actual codebase:
// User copies a connection string
track('connection_string_copied', {
connectionType: 'psql',
connectionMethod: 'transaction_pooler',
connectionTab: 'Connection String',
})
// User enables a feature preview
track('feature_preview_enabled', {
feature: 'realtime_inspector',
})
// User clicks a banner CTA
track('index_advisor_banner_dismiss_button_clicked')
// Experiment exposure (fires on render — valid exception)
track('free_tier_general_region_experiment_exposed', {
variant: 'test',
})
Implementing New Tracking
To add tracking for a user action:
- Name the event: Event Naming
- Choose properties: Property Standards and both Privacy sections. Search
packages/common/telemetry-constants.tsfor similar events and match their property names and casing - Define the event: Event Definitions
- Call
track(): Required Pattern, plus Feature Flag Measurement when a flag gates the behavior - Verify: in the browser network tab, the action sends one
telemetry/eventrequest with the expected properties, and the same action with nothing to change (nothing to close, the same value picked again, a canceled confirmation) sends no result event. Aclickedorsubmittedevent for the click itself still fires