mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +00:00
create-pull-request/patch
44
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d336555617 |
fix(telemetry): redact url params and page titles (#54044)
The frontend apps send the current URL and page title with every analytics event. The redaction added in #53500 and extended in #53955 only covers the `keywords` and `schema` params, so Table Editor filters, search text, invite tokens, OAuth codes and the auth redirect hash still go out in URL properties, and Studio's title carries the table, project and org names. **Changed:** - **Query values are redacted by default**: every `name=value` in a URL property now goes out as `name=redacted`, unless the name is one that attribution reads downstream (`utm_*`, the click ids the first-referrer cookie already collects, `dub_id`, `campaign_id`, `cid`, `promo_code`). Param names and the `?` stay, so reports that match on a param being present keep working. Fixed-vocabulary params such as `tab` are not on the list: nothing reads them today, and several of those names carry customer data on other pages. - **A change to a redacted value no longer sends a pageview**: picking a new filter value on the same page used to send a pageview, which would now be identical to the previous one. The dedupe check compares the redacted URL, so it is skipped. This lowers Studio pageview counts: on current traffic, at most about 9% of dashboard pageviews repeat the previous path with a query string. - **Events from both transports are covered, and the hash is dropped**: `identify` and `group` let the SDK stamp its own `$current_url` with the hash, and `$set_once` pinned that on the person. `before_send` now strips it, and the SDK no longer captures hashes itself. Custom events skip `before_send`, so the same redaction also runs on their `pathname` field, where www was appending the raw query string. The SDK's copy of a search-engine referrer's query (`ph_keyword`) is dropped too. - **Studio sends a route-level title**: `Tables | Database | Supabase` in place of `users | Tables | Database | <project> | <org> | Supabase`. The tab title users see is unchanged, and so are titles in the other apps, which are public content. - **Dead clicks, heatmaps and web vitals are pinned off**: each one puts page text or the page URL in a nested payload the redaction does not walk, and each can be switched on from project settings without a deploy. All three are off today. **Note:** One path is only partly covered. Feature-flag requests carry the first URL and referrer the SDK stored for the browser, and they never pass through `before_send`. The hash is now gone from them; query values in that first URL (for example an invite link opened in a fresh browser) still go out on those requests. ## To test Signed in on the Studio preview, with analytics consent accepted. Check events in the staging analytics project, filtered to the preview host. Tested on the PR preview: - [x] Open the Table Editor, add a filter with the value `leaktest@example.com` and a sort, type `leaktest` in the Tables search and in a logs search, then click through a few pages. Expect no event containing `leaktest`, and `filter=redacted`, `sort=redacted`, `search=redacted` and `s=redacted` in `$current_url`. Observed: zero events from the preview host contained `leaktest`; custom events, `$pageview`, `$pageleave` and `$set` all carried the `=redacted` forms. The filter and sort were applied by loading the Table Editor URL with them, which is how the app restores them - [x] Same session: expect `page_title` and `title` on every event to hold only page names (for example `Tables | Database | Supabase`), with no project, org or table name. Observed: `Table Editor | Supabase`, `Tables | Database | Supabase`, `Postgres Logs | Logs | Supabase`, `Team | Supabase` and similar; no event carried the project, org or table name. `explorer_*` events keep their existing fixed title `Explorer` - [x] Load `/dashboard/project/<ref>?token=leaktest1&projectName=leaktest2#access_token=leaktest3`, then open `/join?token=leaktest4&slug=x`. Expect zero events containing `leaktest`, including `$set`, `$identify` and `$groupidentify`. Observed: zero, with `token=redacted&projectName=redacted` and no hash on any stored URL. `$set` and `$groupidentify` fired and were clean; no `$identify` fired in this session (the user was already identified), so that event was not observed - [x] Load any page with `?utm_source=readable5` appended. Expect `utm_source=readable5` readable in `$current_url`. Observed on Database > Tables with `?utm_source=readable5&gclid=readable6&tab=readable7`: both attribution params readable, `tab=redacted`. The Table Editor route rewrites its own query string and drops unknown params before any event fires, so use another page - [x] Open a table in the Table Editor. Expect the browser tab title to still lead with the table name and include the project and org names. Observed: `<table> | Table Editor | <project> | <org> | Supabase` - [x] On the Table Editor with a filter applied, change the filter value twice, then add a sort. Expect no new `$pageview` for the two value changes and one for the added sort (a new param name). Observed, all through the UI with no reload: adding the filter sent one pageview, the two value changes sent none, adding the sort sent one, and a sidebar navigation sent one; the staging analytics project shows the same four pageviews ## Linear - fixes GROWTH-1572 |
||
|
|
d6e4089b1a |
feat(common): add FrameworkProvider and remove next imports (#53905)
Introduces a lightweight `FrameworkProvider` React context in `packages/common` (`Link`, `Image`, `pathname`, `asPath`, `isReady`, `params`, `push`), wires it up in the consuming apps, and removes the `next` dependency from `packages/common`. **Added:** - `FrameworkProvider`, `useFramework`, `FrameworkLink`, and `FrameworkImage` in `packages/common/framework.tsx`, with plain HTML defaults (`DefaultFrameworkLink` / `DefaultFrameworkImage`). `useFramework().push` always exists and falls back to `window.location.assign` - App-level framework providers wiring `next/link`, `next/image`, and router state in `www` (App + Pages routers), `docs`, `design-system`, `learn`, and `ui-library`, and native TanStack Router bindings in `studio` (`StudioFrameworkProvider`) - `StudioFrameworkProvider` reuses the common defaults (its image only applies the basePath) and reports `isReady` once the first route load commits, so the first page view carries the final route after any redirect - Unit tests for `StudioFrameworkProvider` (`useParams`, `FrameworkLink`, `FrameworkImage`, query/hash-only navigation, `isReady`) and for `PageTelemetry` route-change sends and the `TelemetryTagManager` consent gate **Changed:** - `common/hooks/useParams.ts`: read params from `useFramework()` instead of `next/compat/router` - `common/telemetry.tsx`: replace `next/script` in `TelemetryTagManager` with `useEffect` script injection, and read route state from `useFramework()` in `PageTelemetry` - `common/MetaFavicons/app-router.ts`: drop type-only `Metadata` import from `next` - Moved `MetaFaviconsPagesRouter` to `apps/www/components/MetaFaviconsPagesRouter.tsx` (its sole consumer) - Studio: `toRoutePattern` and `applyBasePath` now live once in `lib/internal-url.ts`, shared by the provider and the `compat/next` shims - `PageTelemetry` throws outside production when no `FrameworkProvider` is mounted, since it would otherwise send only the landing pageview. `useFramework()` itself still falls back to the defaults - `ui-library`: renamed its code-sample framework context to `FrameworkPreferenceProvider` / `useFrameworkPreference` so `FrameworkProvider` only means the `common` one **Removed:** - `learn`'s unused copy of that context (`useCourse` had no callers) - `next` from `packages/common/package.json` peerDependencies App Router adapters set `asPath` to the pathname only, same as the `usePathname`-based telemetry on master (reading search params at the root would opt static pages out of static rendering). ## To test - Run `packages/common` tests and typecheck, and `apps/studio` `StudioFrameworkProvider` / `route-render` / `telemetry` tests - Navigate between routes in Studio, Docs, and WWW and confirm page telemetry fires once per navigation (and does not duplicate on hash-only changes) - Load Studio at `/` (which redirects) and confirm the first page event has the final route - Verify URL params (`useParams`) continue resolving route and search params in Studio --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
c9291259f5 |
fix(studio): don't send duplicate pageviews for exact-URL repeats under TanStack (#53291)
Since Studio moved to the TanStack build (rolling release from Oct 27), it sends a second `$pageview` for the same URL right after the first on several pages. The router compat shim fires `routeChangeComplete` when only the hash changes, which Next never did, so `PageTelemetry` records the page again. On `/sign-in-mfa` this happens when the auth client strips the token hash after an OAuth return. **Changed:** - **One pageview per URL**: `PageTelemetry` remembers the path + query of the last pageview it sent and skips a route change that lands on the same one. Identical-URL repeats were about 40% of `/sign-in-mfa` pageviews and about 12% of all Studio pageviews, up from about 7% before the rollout. - **Filter changes still count**: a query-only change (`?category=security`, `/customers?industry=...`) still sends a pageview. - **Referrer on new signups**: the repeat carries the live `document.referrer` with no first-referrer override, so after an OAuth return it reported the provider's domain. The github.com share of `$initial_referring_domain` on signups roughly doubled after the rollout. `$initial_*` values already written stay as they are. **Note:** I kept the fix out of the shim. A shim filter on TanStack's `pathChanged` would also drop query-change pageviews and stop the command menu closing on same-path query navigations. Identical-URL repeats that predate the rollout are dropped too (for example www `/customers`, which calls `router.replace` on mount), so some Studio page counts will land below their old baseline. ## To test Tested on the Studio PR preview. Run `window.devToolbar()` in the console, open the dev toolbar's Events tab, and filter for `$pageview`: - [x] On any page, run `window.location.hash = 'x'` in the console, expect no new `$pageview` - [x] In a project's Logs, tick a Level filter (query change), expect one `$pageview` per change with the new `?filter=` in its URL - [x] Click from one project page to another, expect one `$pageview` per navigation - [x] Click the sidebar link for the page you are already on, expect no new `$pageview` - [x] Sign in through an external provider (tested with SSO), expect exactly one `$pageview` for `/sign-in-mfa`. The toolbar opens after login, so I checked this one in the staging event data. ## Linear - fixes GROWTH-1491 --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com> |
||
|
|
d862ac18f2 |
feat(telemetry): stamp the app's platform on every event (#53078)
Every first-party PostHog event now carries a `platform` property naming
the supabase.com app that sent it. Each app passes its directory name
(`studio`, `www`, `docs`, `kb`, `learn`, `ui-library`) once at telemetry
setup, and I stamp it on both send paths.
**Changed:**
- **Events sent through the Management API**
(`/platform/telemetry/event`): `buildTelemetryEventRequest` adds
`platform` to `custom_properties`. This also covers kb's search events,
which build the request without `sendTelemetryEvent`.
- **Events sent by posthog-js** (pageviews, page leaves, identify,
experiment exposures): a `before_send` hook stamps `platform` at send
time.
- **App setup**: `PageTelemetry` takes a required `platform` prop, and
kb's island sets the value directly. While unset, the property is left
off instead of defaulting to an app.
**Note:** I used `before_send` instead of `posthog.register()`. Super
properties persist in localStorage, which every supabase.com app shares,
so events sent before `register()` runs would carry the previous app's
value.
**Do not merge yet.** Studio's `trackFeatureFlag` body still needs
`platform`. That commit waits for the Management API change that accepts
the field to reach production, plus an `api-types` regen. The flag-track
body is strict, so sending `platform` early returns 400 on every flag
call.
## To test
On each app's preview, accept cookies and add `?__posthog_debug=true` to
the URL.
- [x] Studio: load a page, expect `$pageview` with `properties.platform:
"studio"` (seen at ingestion: the staging PostHog project has
`$pageview` and `$pageleave` events from the studio-staging preview
host, all with `platform: "studio"`)
- [x] www: load the homepage, expect `send "$pageview"` with `platform:
"www"`; click "Start your project", expect the
`/platform/telemetry/event` request body to have
`custom_properties.platform: "www"` (both seen)
- [x] docs: load a guide, expect `send "$pageview"` with `platform:
"docs"` (seen); added: "Copy as Markdown" sends `custom_properties:
{"pageType":"guide","platform":"docs"}`
- [x] kb: load a page, expect `send "$pageview"` with `platform: "kb"`;
run a search, expect the `/platform/telemetry/event` body to have
`custom_properties.platform: "kb"` (seen on both `kb_search_submitted`
and `kb_search_result_clicked`)
- [ ] learn and ui-library: load a page, expect `send "$pageview"` with
`platform: "learn"` and `"ui-library"` respectively. Not checkable on
previews: learn has no preview deployment, and the ui-library preview
host is not on the consent provider's allowlist, so telemetry never
starts there.
- [x] Added, negative check: on docs, kb and www, no captured posthog-js
event had `platform` unset or set to another app
- [x] Added, ingestion: in the staging PostHog project,
`copy_as_markdown_clicked` (docs) and `start_project_button_clicked`
(www) carry `platform` as a top-level event property
## Linear
- fixes GROWTH-1450
|
||
|
|
5ac0a4843b |
feat(kb): send search and result click telemetry events (#52981)
## Problem KB search sends no events. Part of [DOCS-1514](https://linear.app/supabase/issue/DOCS-1514) (Add telemetry to search). ## Solution Two events through `/telemetry/event`, sent only on platform and after consent: - `kb_search_submitted`: `queryLength`, `resultCount`, `hasResults` - `kb_search_result_clicked`: `resultPath`, `resultPosition` (1-based), `resultCount`, sent with keepalive Query text isn't sent: it can contain personal data. New `buildTelemetryEventRequest` builds the body for `sendTelemetryEvent`. KB posts it with plain `fetch` and no auth header, so no GoTrue client starts on the shared dashboard session. ## Additional context Tested on `astro dev` with Playwright: - `rls`: `{queryLength: 3, resultCount: 10, hasResults: true}` - `zzqxjv`: `{queryLength: 6, resultCount: 0, hasResults: false}` - 2nd result clicked: `{resultPosition: 2, resultCount: 10}`, no `Authorization` header - No consent: nothing sent Also ran `common` and Studio typecheck, KB tests, and `astro build` (no GoTrue in the bundle). ## Review instructions 1. `pnpm --filter kb dev` on platform, accept cookies. 2. Search `rls`, click a result, and check both `/telemetry/event` requests. 3. Decline cookies and repeat: nothing sends. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Kody Jackson <kody.jackson@supabase.io> |
||
|
|
04e72cae1a |
feat(telemetry): track clicks on GitHub example links (#52947)
Docs, www and Studio link to the repo's `examples/` folder from many pages, but we don't record those clicks. PostHog autocapture is off, so we can't tell which examples people open or which pages send them there. **Changed:** - **New `example_link_clicked` event**: I added one capture-phase click listener in `PageTelemetry`. It sends the event when the clicked anchor points at `github.com/supabase/supabase/(tree|blob)/<ref>/examples/<path>`, with `examplePath` set to the path after `examples/`. The source page comes from the event's existing page URL. I put it in `PageTelemetry` so it covers docs, www and Studio without changing individual links, and it sits behind the existing `enabled` and consent gates. - **Survives same-tab navigation**: I added the event to `KEEPALIVE_ACTIONS`, since docs MDX links open GitHub in the same tab. **Note:** middle-clicks and the `window.open` items in the code sample "View source" dropdown aren't counted, so the numbers are a lower bound. ## To test Accept the cookie banner first: the event only sends after consent. Watch the network tab for `POST .../platform/telemetry/event`. Tested on the PR preview: - [x] On `/docs/guides/getting-started/tutorials/with-nextjs`, click "full example on GitHub", expect one request with `action: example_link_clicked` and `custom_properties.examplePath: user-management/nextjs-user-management` (one request, 201, `pathname` set to the docs page) - [x] On `/blog/self-host-maps-storage-protomaps`, click "Find the code", expect one request with `examplePath: storage/protomaps` (201) - [x] On a Studio project's Edge Functions page, click the examples link, expect one request with `examplePath: edge-functions/supabase/functions` (201) - [x] Click a GitHub link outside `examples/` (the GitHub button in the www nav), expect no `example_link_clicked` request (only `homepage_github_button_clicked` fired) - [x] Added: plain same-tab click on the docs link, expect the event to arrive even though the page navigates to GitHub (ingested in staging PostHog about one second after the click) ## Linear - fixes GROWTH-1441 |
||
|
|
ab448c11af |
feat(kb): send PostHog pageview and pageleave after consent (#52533)
## Problem The KB has a consent banner but sends no pageviews. `PageTelemetry` imports Next modules, so it can't run in Astro. Part of [GROWTH-1352](https://linear.app/supabase/issue/GROWTH-1352/add-consent-posthog-tracking-to-new-kb-app). ## Solution - Moved `handlePageTelemetry`, `handlePageLeaveTelemetry` and their first-touch helper into `common/page-telemetry.ts`, with no Next imports. Other apps are unchanged. - Added `PageTelemetryIsland` to the KB layout. After consent it sends one `$pageview` per page load and `$pageleave` on `beforeunload`. First-touch UTMs and the `_sb_first_referrer` and mw-diag cookies go only on a tab's first pageview after consent (a `sessionStorage` flag) or on arrival from an external site. - Needs `NEXT_PUBLIC_POSTHOG_KEY` and `NEXT_PUBLIC_POSTHOG_HOST` (`https://ph.supabase.com`) on the KB Vercel project. Both are set on Preview and Production. ## Review instructions 1. Check the `telemetry.tsx` removals match `page-telemetry.ts`. 2. On a KB preview page, accept cookies and check the network tab for `$pageview`, then `$pageleave` after navigating. KB and studio telemetry tests pass. From the kb preview, PostHog prod received `$pageview` on `/kb`, `$pageleave` on `/kb`, then `$pageview` on `/kb/guides/migrate-from-neon`. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) |
||
|
|
a7cf044118 |
feat(telemetry): capture ChatGPT Ads oppref click id (GROWTH-1278) (#51397)
## Problem ChatGPT Ads appends an `oppref` click id to landing URLs. We don't read it, so ChatGPT ad signups show up in PostHog with no click id and the first-referrer cookie doesn't treat the visit as paid. GROWTH-1278 ## Solution - Add `oppref` to the first-touch click ids sent with PostHog events (`telemetry.tsx`) - Add `oppref` to `CLICK_ID_KEYS` in `first-referrer-cookie.ts`, so it is stored in `_sb_first_referrer` and counts as a paid signal Conversion reporting to OpenAI itself goes through GTM, so it isn't part of this PR. ## Review instructions 1. Run `pnpm exec vitest run first-referrer-cookie` in `packages/common`. The `hasPaidSignals` test now covers `oppref`. 2. On the preview, load any page with `?oppref=test` and check the first-touch event in PostHog carries `oppref`. ## Checklist Check all before review: - [ ] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
a9078612f2 |
fix(www): stop cross-zone link prefetch (#51066)
About 95% of the 404s served on supabase.com are App Router RSC prefetches (`?_rsc=`) that www `<Link>`s fire at paths another zone serves: `/docs`, `/dashboard`, `/library`, and the footer's `humans.txt`, `lawyers.txt` and `security.txt`. Next.js can't prefetch or client-navigate across multi-zone boundaries, so each prefetch 404s even though the link itself works. I turned every www link into another zone into a plain `<a>` and added a lint rule so new ones stay that way. **Changed:** - **Cross-zone links are plain anchors**: links that always leave www (literal `/docs`, `/dashboard` and `.txt` hrefs, absolute `https://supabase.com/dashboard` URLs, the `getDashboardCtaHref` CTAs) render `<a>`. Renderers whose href comes from data (nav, footer, plan and add-on CTAs, product cards) branch on `isCrossZoneHref`, which reads the zone list from `lib/rewrites.js`. In-zone links stay `<Link>` and keep prefetching. - **New literal links can't regress**: `www/no-cross-zone-link` errors on a `next/link` `<Link>` whose literal or template href points at another zone. It evaluates `lib/rewrites.js` as production, so `/docs` counts in every environment. - **Click tracking survives the full navigation**: `sign_in_button_clicked`, `start_project_button_clicked` and `www_pricing_plan_cta_clicked` now send with `keepalive`, like `sign_in_submitted` already did, so an immediate page load can't cancel them. The mobile nav Sign in and Start your project buttons used `legacyBehavior`, which never called their `onClick`: PostHog has no `Mobile Nav` location for either event in the last 30 days. Those clicks report from this PR on. - **Typecheck no longer crashes**: the functions page's default export inferred a type through `RealtimeLogs`'s unexported `Props`, which makes the native TypeScript compiler panic during `tsc --noEmit`. I exported `Props`. **Note:** the lint rule only sees literal hrefs. A new renderer whose href comes from data needs its own `isCrossZoneHref` branch, and review is the only check on that. ## To test `/docs` is only rewritten on production and absolute `https://supabase.com/...` links are cross-origin on a preview, so the preview proves the relative non-docs cases (`/dashboard*`, `/library`, the footer .txt files). `/docs/...` prefetches still appear on the preview because it has no docs rewrite. Tested on Vercel preview: - [x] Open `/` with the network tab filtered to `_rsc` and scroll to the footer: no requests for `/dashboard*`, `/library`, `/design-system`, `/kb`, `/evals`, `/humans.txt`, `/lawyers.txt` or `/.well-known/security.txt`, while in-zone ones such as `/pricing`, `/features` and `/blog` still appear - [x] Same check on `/pricing`, `/auth`, `/database`, `/storage`, `/realtime`, `/edge-functions`, `/blog` and a blog post: no `_rsc` requests to `/dashboard*`, `/library` or the footer .txt files - [x] Open the Developers dropdown on desktop and the mobile menu at 390px: no new `_rsc` requests to `/dashboard*` or `/library` - [x] Click header Docs, footer Humans.txt, the hero Start your project button and the pricing Free plan button: each lands where it did before (`/docs`, `/humans.txt` text, `https://supabase.com/dashboard/sign-up`, `https://supabase.com/dashboard/new?plan=free`). Signed out, the Free plan button lands on the dashboard sign-in with `plan=free&returnTo=%2Fnew` - [x] Click the hero Start your project button: the `/platform/telemetry/event` POST with `start_project_button_clicked` completes with a 2xx after the page starts navigating. 201 with the navigation held; on the real navigation the event still reached staging PostHog - [x] At 390px, open the mobile menu and click Sign in: a `/platform/telemetry/event` POST with `sign_in_button_clicked` and `buttonLocation: "Mobile Nav"` fires. Start your project in the same menu also sends `start_project_button_clicked` with `buttonLocation: "Mobile Nav"` - [ ] Signed in, load `/`: no `/dashboard/projects?_rsc=` request (not run: the preview origin has no signed-in session) - [x] Open the desktop Product dropdown and the Product section of the 390px mobile menu: Compute shows its Private Alpha badge and the other products show none (checks the master merge into `MenuItem`) After deploy, `/` and `/pricing` on supabase.com show no `_rsc` requests to `/docs*`, `/dashboard*` or `/library`. After a full day, the share of supabase.com 404s carrying `_rsc=` should drop from about 95% to under 10%, and `sign_in_button_clicked` and `start_project_button_clicked` should start showing a `Mobile Nav` location in PostHog. ## Linear - fixes GROWTH-1294 |
||
|
|
4a941518e3 |
feat(studio): track Explorer runs and saves (#51004)
I added outcome events for Explorer query runs and successful manual notebook saves. Existing page visits and preview toggles do not show whether users complete queries or persist notebooks. **Changed:** - **Query usage:** Accepted runs from query tabs and notebook cells emit submitted and terminal outcome events with a shared run ID. Canceled confirmations emit no run events. - **Notebook adoption:** Successful manual saves emit created or updated events. Recreated notebooks count as creations. Unsaved drafts and failed saves emit neither. - **Event metadata:** Explorer action events use `Explorer` as their page title. **Note:** Assistant-generated saves are outside this PR. Custom properties omit SQL and notebook content. Page visits still carry the browser title, which can include a notebook name. ## To test Tested on the staging preview: - [x] Run valid and invalid SQL from an Explorer query tab. Each run emits one submitted event and one matching completed or failed event with the same run ID. - [x] Run database and Logs notebook query cells, then add a markdown cell. The query cells emit matching event pairs; the markdown cell emits no query event. - [x] Save a new notebook, then edit and save it again. The successful saves emit created and updated events. - [x] Cancel a guarded query. It emits no query run event. - [ ] Recreate a notebook deleted on the server after local edits. A successful save emits created, not updated. - [x] Inspect an Explorer action event request. Its page title is `Explorer`; page visits still use the browser title. - [ ] Force a notebook save failure. It should emit no save event. This case was not tested manually. ## Linear - fixes GROWTH-1298 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Analytics** * Explorer query runs are tracked for database and log queries, including whether they complete or fail. * Query activity is associated with its location in Explorer, such as a query tab or notebook cell. * Successful notebook saves are tracked as creations or updates. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
66e6cd1639 |
feat: capture Freebuff ad click ids (#50181)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature: ad attribution capture. ## What is the current behavior? Freebuff ad clicks arrive on supabase.com with a signed click id in `?bfcid=`. Nothing captures it, so those signups are unattributed. ## What is the new behavior? This PR captures `bfcid` and writes it to a cookie that, in production, is scoped so the management API receives it. The conversion is reported server-side on profile creation, in a separate change tracked in GROWTH-1217. Start with `enforceConsentDecision` in `packages/common/consented-url-cookie.ts`. It is the rule everything else hangs off, and `consented-url-cookie.test.ts` covers the state matrix. Capture: - `bfcid` is read on landing and held in `sessionStorage` until the consent decision resolves. Memory alone loses it when someone navigates before answering the banner. - Once consent is granted it goes into a cookie. In production on `*.supabase.com` that cookie is scoped to `domain=supabase.com`, and it is host-only elsewhere. It is written only after consent, which is the signal GROWTH-1217 relies on. - Values are validated with `/^bfc_[A-Za-z0-9._-]{1,508}$/`, the validator Freebuff publishes in their tag, so we never store a value their tag would reject. - `bfcid` is added to the first-touch attribution props, which feed pageview telemetry and are already consent-gated. Consent: - `enforceConsentDecision` reduces the decision to two states. Undecided and declined both clear the cookie, since neither has consent to point at. They differ in the retained value: an undecided visitor may still accept, so it waits for them. - `clearConsentedUrlCookie` drops the cookie. `discardConsentedUrlValue` also drops the retained value. - A module-level valtio subscription registers on import, guarded on `window` so it is inert during SSR. `packages/common/consent-state.ts` gains a generic `isResolved` flag and no vendor knowledge. A consumer acting on a decision needs to tell "not decided yet" from "decided against", which `hasConsented` cannot express alone. `applyPriorDecisionToSDK` now returns its promise chains, so its signature becomes `void | Promise<void>` and initialization awaits settlement before marking the decision resolved. Worth checking the call sites. ## Additional context 160 tests pass in `packages/common`. Typecheck and Prettier are clean locally on the changed files. CI is still running on the latest commit. Unverified: the clearing paths are covered by unit tests only. The consent SDK is short-circuited in local and preview builds, so they cannot be exercised outside production. An end-to-end conversion recorded by Freebuff is also unverified, since it needs the server-side change deployed. GROWTH-1216 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added consent-aware handling for Freebuff Ads click identifiers, retaining valid URL values until consent is resolved and storing them in a cookie after approval. - Added automatic cleanup when consent is denied or withdrawn, while preserving unrelated cookies. - Added support for capturing the click identifier in first-touch attribution data. - **Bug Fixes** - Improved consent initialization tracking so completion is reported after successful or failed resolution. - Added safeguards for restricted browser storage, cookies, and server-rendered environments. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Sean Oliver <882952+seanoliver@users.noreply.github.com> |
||
|
|
5db8a0e960 |
feat(studio): instrument sign-in attempts and failures (#49853)
The /sign-in page emitted only a pageview on entry and the success-side `sign_in` event on exit: failed or abandoned attempts were invisible, so "never interacted" and "tried and failed silently" could not be told apart in the sign-in funnel. I added an unsampled `sign_in_submitted` event at every initiation point and classified failure capture via `dashboard_error_created` with a new `signin` origin. **Changed:** - **Submit attempts observable**: `sign_in_submitted` (method: `email`, provider id, `sso`, or partner) fires from the DOM submit handler on the password and SSO forms (so submits that fail client-side validation still count), and from the OAuth, custom-provider, and partner initiation handlers. - **Failures classified**: each sign-in error path feeds the existing funnel-error pipe with origin `signin` and a controlled reason slug (`invalid_credentials`, `email_not_confirmed`, `captcha_failed`, `sso_provider_not_found`, ...). GoTrue auth errors now classify via their numeric `status`, guarded so transport failures (`status: 0`) stay `network_error`. - **Attempt events survive the OAuth redirect**: the telemetry event POST sends with `keepalive` (scoped to `sign_in_submitted`, since keepalive requests share a per-page in-flight body quota), so a dispatched request is no longer aborted by the provider navigation; send rejections are caught centrally instead of surfacing as unhandled rejections. The fetch still dispatches after an async token lookup, so preview testing verifies the GitHub-path event actually lands on the wire. - **Captcha rejection is no longer silent**: a rejected hCaptcha challenge resolves the stuck loading toast with an error message, emits `captcha_challenge_failed` (distinct from `captcha_failed`, which stays reserved for the auth server rejecting a submitted token), reports to error monitoring, and resets the captcha widget (previously: unhandled promise rejection and a spinner that never resolved). - **Partner method validated**: the partner sign-in page resolves the URL-hash value against the provider registry and forwards the canonical provider id into `method` on both `sign_in_submitted` and `sign_in`; anything unregistered records as `unregistered_partner`, so a crafted link can't poison the breakdown on either event. **Note:** failure events stay on the shared 10% `dashboard_error_created` sampling rate (a per-origin carve-out would break cross-source volume comparability); the unsampled attempt event carries the tried-vs-never-interacted signal at full volume. ## To test Tested on Vercel preview (studio-staging, wire-level network capture + staging ingestion check): - [x] On `/sign-in`, submit a bogus email + password: expect a `POST */platform/telemetry/event` request with `action: sign_in_submitted`, `method: email` in the network tab, plus an error toast. Observed: 201, auth returned 400 as expected. - [x] Submit with an empty password: expect `sign_in_submitted` to still fire (validation failures count as attempts). Observed: event fired with 201 and no auth call followed. - [x] Click "Continue with GitHub": expect `sign_in_submitted` with `method: github` on the wire before the provider redirect. Observed: the POST completed (201) before the browser landed on github.com, so the keepalive path holds. - [x] Negative case: fresh page load with no interaction fires no `sign_in_submitted`. - [x] Ingestion: all fired events (methods `email`, `github`, plus organic `sso` submits from a real login on the same preview) arrived in the staging project with the expected properties. - [x] Re-ran the email and GitHub paths on the scoped-keepalive build (`129bf8d`): both `sign_in_submitted` POSTs returned 201 (the GitHub one completed despite the provider redirect), and both events ingested into the staging project with the expected `method`/`category` properties. ## Linear - GROWTH-1165 (no `fixes` keyword on purpose: the evidence checks run on prod data post-deploy, and the issue closes manually after they pass) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved sign-in protection with more reliable invisible CAPTCHA handling. * Added sign-in submission tracking across password, SSO, partner, custom OAuth, and external-provider flows. * Added detailed classification for authentication, validation, CAPTCHA, provider, and network errors. * **Bug Fixes** * Sign-in now stops safely and resets CAPTCHA when verification fails. * Improved error reporting for failed sign-in attempts, including redirects and OAuth flows. * Ensured sign-in telemetry is delivered reliably during OAuth redirects. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
e88a3723e1 |
feat(studio): add PostHog session replay with masked-by-default policy (#48515)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Telemetry feature. ## What is the current behavior? - Session replay is off, and nothing in the code keeps it off. - `packages/common/posthog-client.ts` sets no recording config at all. - So PostHog's project setting alone decides, for every app sharing that project. - Studio, www and docs share one project. - Studio shows customer data almost everywhere: SQL editor, table rows, connection strings, API keys. - posthog-js masks inputs by default. It does not mask rendered text. - [GROWTH-1055](https://linear.app/supabase/issue/GROWTH-1055) ## What is the new behavior? - `posthogClient.init()` takes a masking config, and disables recording when it gets none. - Studio passes one behind `NEXT_PUBLIC_POSTHOG_SESSION_REPLAY`. - Every other app passes nothing, so it never loads the recorder. - Studio masks all text and all inputs. - `data-ph-capture="true"` opts one element's text back in. Unused so far. - Canvas is blocked, because it records as images that text masking cannot reach. - Query strings and fragments are stripped from recorded URLs, where auth callbacks carry tokens. - Request and response bodies are never recorded. - Console logs are never recorded, since masking only reaches DOM text. - Masking is set in code, so PostHog's settings cannot loosen it. - Consent gating is unchanged. Nothing records before a user accepts. ## Additional context - Recording needs three things: this env var, the PostHog project toggle, and user consent. - All three are off or unset, so merging this changes nothing at runtime. - `NEXT_PUBLIC_POSTHOG_SESSION_REPLAY` goes into Vercel on Preview scope first, to test on a preview build. - Production scope comes later, once we are ready to record there. - `NEXT_PUBLIC_*` is inlined at build time, so each scope needs a rebuild afterwards. - Text inside HTML attributes (`title`, `alt`, `href`) is still recorded as-is. - posthog-js exposes no hook for masking attributes, so covering it needs `ph-no-capture` per component. - Staging has no server-side masking config, so that is where this gets verified. - Plan: enable recording on staging, verify masked text on a preview, then decide on production. - Network timing stays on for the dashboard performance work. Payloads stay off. - Tests cover both masking functions and the config values. ## Screenshots https://github.com/user-attachments/assets/aa064a04-f977-4453-a3da-2fe0cdcead08 <img width="889" height="651" alt="CleanShot 2026-07-31 at 10 13 43" src="https://github.com/user-attachments/assets/f1d07946-fd68-42b2-89f1-d201bc605638" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit * **New Features** * Added privacy-focused session replay for Studio. * Text and form inputs are masked by default, with explicit opt-in capture. * Network recordings remove query strings and fragments. * Headers, request bodies, canvas data, and console logs are excluded. * **Bug Fixes** * Improved whitespace and capture-attribute handling during masking. * Session replay remains disabled without a masking policy or explicit enablement. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
856b2badf7 |
feat(telemetry): mirror signup_timestamp to PostHog person property (#45951)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature — tiny telemetry addition. +7/-1 in one file. ## What is the current behavior? [PR #45946](https://github.com/supabase/supabase/pull/45946) added `org_count` as a PostHog person property to unblock targeting on org membership. But `org_count` is set on every authenticated session (the `Telemetry` component fires identify whenever `user.id` + `organizations` resolve), not just at signup completion. That means flag filters like `person.org_count == 1` match two populations: - Brand-new dashboard signups currently in their first org (intended) - Returning users who happen to have one org and just signed in (not intended) For the upcoming `dataApiRevokeOnCreateDefault` experiment, this contaminates the activation comparison because the "returning single-org" group can't activate (they already did, months ago), diluting the measured effect. ## What is the new behavior? Adds `signup_timestamp: user.created_at` to the existing `posthogClient.identify` call in `useTelemetryIdentify`. Since gotrue's `user.created_at` is immutable, the value stays constant across sign-ins — no need for `$set_once` semantics, no race with anonymous activity, no cohort refresh lag. Flag targeting can now combine `person.org_count == 1 AND person.signup_timestamp >= <experiment_start_date>` to cleanly scope to brand-new signups. ## Testing No new unit tests added — the existing `useTelemetryIdentify` function has no test file, the change is one additional field on an existing call, and the property's correctness is verifiable end-to-end (sign up → check PostHog person record). Adding to the test ticket [GROWTH-854](https://linear.app/supabase/issue/GROWTH-854) for coverage along with the broader posthog-client wrapper tests. ## Additional context Ref: [GROWTH-853](https://linear.app/supabase/issue/GROWTH-853) This is the follow-up gate before the 5% rollout of `dataApiRevokeOnCreateDefault` — without this, the experiment would mix brand-new signups with legacy single-org users on sign-in. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Enhanced telemetry and analytics data collection for signed-in users by improving user identification tracking and adding signup timestamp information for better analytics insights. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/45951) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
7f5865872a |
Enforce noUnusedLocals and noUnusedParameters in tsconfig.json + fix all related issues (#45264)
## Context Enforce `noUnusedLocals` and `noUnusedParameters` in tsconfig.json + fix all related issues |
||
|
|
273102323d |
feat(growth): filter OAuth/SSO redirect referrers from attribution (#44405)
## Problem GitHub OAuth redirects and Google SSO set the browser's Referer header to their domain when redirecting back to supabase.com. Our attribution pipeline treats these as genuine referral traffic, inflating the `github` channel by ~20K orgs/week. The internal referrer fix (GROWTH-647) surfaced this by reducing `unknown-internal` — it didn't cause the issue, it revealed OAuth noise that was previously hidden. ## What happened When users sign in with GitHub, the browser sends `Referer: https://github.com/`. GitHub's login pages use `origin-when-cross-origin` Referrer-Policy, which strips the path. So OAuth redirects arrive as bare `github.com/` — indistinguishable from a direct visit to github.com. Meanwhile, genuine GitHub referrals from repos/READMEs always include the full path because those pages use `no-referrer-when-downgrade`. We validated against `mart_marketing_organization_attribution`: 98.5% of GitHub-attributed orgs have bare `github.com/` as the referrer. Only ~250/week have specific paths (genuine referrals). ## Changes - Added `isOAuthRedirectReferrer()` to `first-referrer-cookie.ts` — identifies auth provider redirects: - `accounts.google.com` blocked entirely (dedicated SSO subdomain) - Bare `github.com/` blocked (OAuth redirect signature) - `github.com/<specific-path>` preserved (genuine repo/README referrals) - Wired into `shouldRefreshCookie()` so OAuth referrers never get stamped into cookies - Wired into `handlePageTelemetry()` referrer overrides as defense-in-depth - 17 new tests covering all OAuth patterns and edge cases ## Testing All 52 tests pass. New tests cover Google SSO (bare + with path), GitHub bare domain (with/without trailing slash), genuine GitHub referrals (repo, README, discussion, blob), explicit OAuth path, non-OAuth domains, empty/malformed URLs. Verified TDD — tests failed red before implementation, green after. Companion dbt PR in data-engineering handles historical data. GROWTH-732 |
||
|
|
c8e98cec0e |
feat(growth): in-memory first-touch attribution store (#43570)
## Changes Introduces two new files in `packages/common`: - **`telemetry-first-touch-store.ts`** — a module-scoped singleton that holds first-touch attribution data (referrer, UTM params, page URL) in memory. Writes once on first load, cleared after the initial pageview event fires or on opt-out. No device storage involved. - **`useFirstTouchStore.tsx`** — a React hook that captures attribution data on initial page load and writes it into the store, gated on the `enabled` flag so it only runs where consent has been handled. Trade-off: data is lost on a hard reload before consent is granted — accepted edge case per GROWTH-656. Follows the same module-scope pattern already used by `posthogClient` and `consentState`. ## Testing - Verify first-touch data is captured on initial load and readable by `PageTelemetry` after consent - Verify no cookie is set before consent - Verify data is cleared after initial pageview fires GROWTH-656 |
||
|
|
01c178e159 |
chore(studio): graduate homeNew experiment (#43437)
## Summary
The `homeNew` PostHog experiment has concluded. This PR graduates it by
making the new homepage (`ProjectHome`, formerly `HomeV2`) the permanent
default for all users, and removes all dead code from the old
experiment.
## Changes
- Remove `homeNew` PostHog feature flag checks and `home_new` experiment
exposure tracking from 3 files
- Rename `HomeNew/` → `ProjectHome/` directory and `HomeV2` →
`ProjectHome` export
- Delete old `Home/Home.tsx` component (shared components like
`ProjectList/` are kept — still used by org pages)
- Delete `pages/project/[ref]/building.tsx` and add a server-side
redirect from `/project/:ref/building` → `/project/:ref` to prevent 404s
during rollout (old cached JS bundles may still route to `/building`)
- Simplify `ContentWrapper` building-state logic in `ProjectLayout` —
always redirect building projects to home, always suppress building
interstitial on home page
- Always route to `/project/{ref}` after project creation (remove
`/building` path)
- Update all Observability imports from `HomeNew` → `ProjectHome`
## Self-hosted behavior change
Self-hosted Studio previously showed the old `Home` component (client
libraries + example projects) since PostHog flags don't load. This PR
changes self-hosted to show `ProjectHome` (TopSection with service
status + instance diagram, advisor, custom reports). All sections query
backend APIs that exist on self-hosted. E2E tests pass against the
self-hosted build.
## Testing
- [x] `pnpm turbo run build --filter=studio` passes
- [x] No remaining references to `homeNew`, `home_new`, or `HomeNew` in
codebase
- [x] No broken imports to deleted files
- [x] Self-hosted E2E tests pass (145 passed, 1 flaky, 4 skipped)
- [x] `/building` redirect added to both platform and self-hosted config
blocks
**Quick test:**
1. Navigate to any project homepage — should render the ProjectHome
component
2. Create a new project — should redirect to `/project/{ref}` (not
`/building`)
3. Visit a project in `COMING_UP` state on a non-home route — should
redirect to home
4. Visit `/project/{ref}/building` directly — should 302 redirect to
`/project/{ref}`
## Linear
- fixes GROWTH-671
|
||
|
|
8ebbad3a5b |
feat(growth): expand www middleware to /dashboard and /docs (Phase 1 - instrumentation only) (#43413)
## Problem The `_sb_first_referrer` cookie isn't working. The www middleware matcher explicitly excludes `/dashboard` and `/docs`, so the cookie never gets stamped for Studio or Docs traffic. PostHog confirmed: only 1 event with `first_referrer_cookie_present=true` out of ~46.5M Studio pageviews in the last 7 days. ## Background: what the matcher does In Next.js, the `matcher` config controls which incoming requests the middleware function even runs on. If a path doesn't match, the middleware is skipped entirely — the request passes through untouched. If it matches, the middleware runs and can mutate the response (set cookies, headers, etc.). This matters because Studio's SPA navigation works via silent `/_next/data/` JSON fetches. If middleware runs on those requests and returns `NextResponse.next()` with any mutations, it breaks those fetches and causes full page reloads instead of client-side transitions. ## What we tried before | PR | www runs on `/dashboard`? | Studio `proxy.ts` runs on all routes? | Result | |---|---|---|---| | **#42768** (Attempt 1) | ✅ Yes — and also intercepts `_next/data` | ✅ Yes — `matcher` config removed, stamps cookie everywhere | Full page reloads in Studio | | **#43129** (Full revert) | ❌ No — www middleware deleted entirely | ❌ No — restored to `matcher: '/api/*'` only | Back to baseline, no cookie stamping anywhere | | **#43153** (Attempt 2) | ❌ No — `/dashboard` explicitly excluded | ✅ Yes — `matcher` config removed again, stamps cookie everywhere | Full page reloads in Studio again | | **#43189** (Attempt 3) | ❌ No — same as #43153 | ✅ Yes — `matcher` config still removed, cookie stamping made conditional | Still broken | | **#43190** (Ivan's fix) | ❌ No — `/dashboard` still excluded | ❌ No — restored to `matcher: '/api/*'` only | Works — but cookie never stamps for `/dashboard` traffic | | **#43413** (this PR) | ✅ Yes — sets diagnostic cookie only, no attribution stamping yet | ❌ No — unchanged, still `matcher: '/api/*'` only | ❓ Untested in prod | The common factor in every failure: Studio's `proxy.ts` ran on all routes (including `_next/data` requests), which broke SPA navigation. This PR is the first one that runs www middleware on `/dashboard` while Studio's `proxy.ts` stays in its original narrow `/api/*` scope. ## What changed This is Phase 1 of a two-phase rollout. We remove `dashboard|docs` from the matcher's negative lookahead so www middleware runs on those paths — but instead of stamping cookies, we set a short-lived (60s) diagnostic cookie `_sb_mw_diag` on `/dashboard` and `/docs` requests. The diagnostic cookie encodes `hit=1&would_stamp={0|1}&has_cookie={0|1}`, which Studio telemetry reads on the initial pageview and reports to PostHog as `mw_diag_hit`, `mw_diag_would_stamp`, and `mw_diag_has_existing_cookie` properties. A cookie rather than a header because response headers aren't readable by JS. It also tests the actual Set-Cookie mutation path that Phase 2 will use (which is what Next.js issue #41885 is specifically about). Phase 1 answers two key questions before we commit to Phase 2: 1. Does expanding the matcher break Studio SPA navigation? 2. What % of /dashboard arrivals would get a first-referrer cookie stamped in Phase 2? ## Phase 2 readiness criteria **Important caveat**: `mw_diag_*` data reflects consented users only and may under-represent first-visit anonymous traffic. The Phase 2 decision should account for this — the actual middleware execution rate is likely higher than what PostHog reports. ### PostHog query spec **Middleware execution rate**: Of all Studio initial pageviews on `/dashboard` or `/docs` paths, what percentage have `mw_diag_hit = true`? Expected: >= 90%. Below 70% warrants investigation (could indicate edge caching bypassing middleware, or a matcher configuration issue). ``` Filter: event = "$pageview" AND (current_url contains "/dashboard" OR current_url contains "/docs") Breakdown: mw_diag_hit (true vs null/missing) Metric: count(mw_diag_hit = true) / count(all) * 100 ``` **Would-stamp rate**: Of events with `mw_diag_hit = true`, what percentage have `mw_diag_would_stamp = true`? This tells us what percentage of Phase 2 traffic would actually get a cookie stamped. No hard threshold — unexpected values (< 5% or > 95%) suggest a logic bug worth investigating before Phase 2. ``` Filter: event = "$pageview" AND mw_diag_hit = true Breakdown: mw_diag_would_stamp (true vs false) Metric: count(mw_diag_would_stamp = true) / count(all) * 100 ``` **Existing cookie rate**: Of events with `mw_diag_hit = true`, what percentage have `mw_diag_has_existing_cookie = true`? This tells us how many users already have the cookie from a prior www visit. ``` Filter: event = "$pageview" AND mw_diag_hit = true Breakdown: mw_diag_has_existing_cookie (true vs false) Metric: count(mw_diag_has_existing_cookie = true) / count(all) * 100 ``` ### Go / no-go threshold table | Signal | Go | Investigate | No-Go | |---|---|---|---| | `mw_diag_hit` rate (% of /dashboard+/docs pageviews) | >= 90% | 70-90% | < 70% | | SPA navigation errors (Sentry / Vercel logs) | No increase | < 0.1% increase | > 0.5% increase | | Middleware p99 latency (Vercel function logs) | < 50ms added | 50-100ms | > 100ms | | Sample volume in first 24h | > 1,000 events | 100-1,000 (extend window) | < 100 (insufficient data) | ## Changes - `apps/www/middleware.ts`: Removed `dashboard|docs` from matcher; added `isDashboardOrDocs` guard that sets `_sb_mw_diag` diagnostic cookie instead of stamping attribution - `apps/www/middleware.test.ts`: 12 tests covering cookie stamping on www paths, diagnostic cookie encoding for all scenarios (external referrer, direct nav, internal referrer, existing cookie) - `packages/common/first-referrer-cookie.ts`: Exported `MW_DIAG_COOKIE_NAME`, `MwDiagData` type, and `parseMwDiagCookie()` helper - `packages/common/telemetry.tsx`: Reads `_sb_mw_diag` on initial Studio pageview; reports `mw_diag_*` properties to PostHog ## Testing Unit tests pass (13/13 www, 31/31 first-referrer-cookie). Production validation needed: - [ ] Studio SPA navigation works (tab changes, SQL editor, no full page reloads) - [ ] PostHog shows `mw_diag_hit = true` on Studio initial pageviews - [ ] `mw_diag_would_stamp` distribution looks reasonable before enabling Phase 2 - [ ] Monitor 24h before Phase 2 Ref: GROWTH-625 / GROWTH-668 |
||
|
|
45120155d2 |
feat: Fetch the google scripts only if consent is accepted (#43221)
This pull request improves how user consent is handled for telemetry and tracking, ensuring that analytics scripts and cookies are only active when the user has provided consent. The changes both enforce stricter checks before enabling Google Tag Manager and ensure that tracking cookies are cleared when consent is denied. |
||
|
|
75ec7c6e6b |
feat(growth): re-land first-referrer cookie attribution with fixed middleware matchers (#43153)
## Summary Re-lands the first-referrer cookie feature from #42768 (reverted in #43129) with middleware matcher fixes that prevent Studio traffic interference. **Tracks:** [GROWTH-651](https://linear.app/supabase/issue/GROWTH-651) ## What changed New shared module in `packages/common/first-referrer-cookie.ts` that handles stamping and parsing a first-referrer cookie (referrer, UTMs, click IDs, landing URL). Each app's middleware calls `stampFirstReferrerCookie` on the edge response — www and docs are the primary entry points, Studio is a fallback for direct visits with UTMs. On the telemetry side, `handlePageTelemetry` now takes an options object instead of positional args, reads the cookie on initial pageview, and overrides the referrer if the cookie captured an external source but the current referrer is internal (i.e., the user navigated cross-app). Also sends `first_referrer_cookie_present`/`consumed` properties so we can observe the handoff in PostHog. The docs middleware matcher was broadened from `/reference/:path*` to all docs pages so we stamp cookies site-wide, not just on reference paths. ## Root cause of original revert Two layers: 1. **Matcher gap**: www middleware ran on `/dashboard/*` traffic in prod due to Vercel Multi-Zone architecture (www is the gateway for `supabase.com`, proxying `/dashboard` → Studio, `/docs` → Docs). Middleware runs *before* rewrites, so www middleware executed on all proxied traffic. 2. **`_next/data` interception**: The matcher didn't exclude `_next/data` paths. Client-side navigation in Next.js fetches JSON via `/_next/data/...` — middleware intercepted these, returned `NextResponse.next()` with cookie mutations (which processes through the middleware response pipeline), and this interfered with the JSON responses, causing full page reloads in the SQL editor. ## How this PR fixes it | Fix | Detail | |---|---| | Exclude `_next/data` | All three matchers (`www`, `docs`, `studio`) exclude `_next/data` via negative lookahead | | Exclude `dashboard` + `docs` from www | www middleware no longer runs on proxied app traffic | | `/api/` path guard in Studio | Broadened matcher requires explicit path check for API route filtering | | `NextResponse.next()` semantics | Cookie stamping only happens on matched paths; unmatched paths never enter middleware | ### `NextResponse.next()` vs `undefined` nuance Returning an explicit `NextResponse.next()` with cookie mutations processes through Next.js's middleware response pipeline (headers are merged, cookies are set). Returning `undefined` (i.e. the request never matches the matcher) lets Next.js handle the request completely untouched. The matcher exclusions ensure `_next/data` and proxied app paths never enter middleware at all. ## Testing - ✅ 22 unit tests for shared cookie utilities (all pass) - ✅ Studio prod build succeeds, middleware recognized as `ƒ Proxy (Middleware)` - ✅ Playwright validation: client-side navigation works across 3 page transitions, `_next/data` requests return 200 OK without middleware interception, no full-page reloads - ❌ www/docs SSG builds require platform backend services (expected — same as master) |
||
|
|
85e6b1143f |
chore: Revert "fix: persist first referrer across app boundaries (#42768)" (#43129)
This reverts commit https://github.com/supabase/supabase/commit/04e63dfb2e00c43f8c57e538b8056aa647f4e5b4 since it was causing the Studio app to rerender the full page on every link navigation. |
||
|
|
04e63dfb2e |
fix: persist first referrer across app boundaries (#42768)
## Summary Fixes GROWTH-625. Preserves first-touch attribution across app boundaries by persisting external referrer context at the edge and consuming it on Studio's initial pageview. When users come from an external source to www/docs and then navigate to Studio, Studio often only sees the internal `supabase.com` hop. This change preserves the original external context so first-touch attribution is retained. ## What changed - **Shared first-referrer cookie utilities** (`packages/common/first-referrer-cookie.ts`): - `isExternalReferrer`, `buildFirstReferrerData`, `serializeFirstReferrerCookie`, `parseFirstReferrerCookie` - `hasPaidSignals` — detects click IDs (gclid, fbclid, etc.) and paid utm_medium values - `shouldRefreshCookie` — centralizes stamp-or-skip decision for all apps - `stampFirstReferrerCookie` — shared middleware helper used by all apps (extracted from duplicated inline logic) - **Edge middleware on all apps** — stamps cookie for external visitors, refreshes on paid signals: - `apps/www/middleware.ts` (simplified to use shared helper) - `apps/docs/middleware.ts` (simplified to use shared helper) - `apps/studio/proxy.ts` (integrated into existing proxy file) - **Docs middleware matcher** — broadened from `/reference/:path*` to all non-static paths so the first-referrer cookie is stamped on all docs pages, not just reference paths - **Telemetry** — Studio consumes cookie on initial pageview (`packages/common/telemetry.tsx`). `handlePageTelemetry` refactored from 7 positional params to an options object for readability. - **Tests** — 22 unit tests covering all utilities and edge cases (including direct-navigation scenario) ## Behavior - Writes `_sb_first_referrer` cookie when: - cookie is not already set and request has an external referrer, OR - cookie exists but incoming URL has paid traffic signals (click IDs or paid utm_medium) - Cookie: 365-day TTL, `domain=supabase.com`, `sameSite=lax`, `secure=true` in production - On first Studio pageview, if current referrer is internal and cookie has external context: - use persisted external referrer - apply persisted UTM/click-id/landing-url attribution props - Measurement properties: `first_referrer_cookie_present`, `first_referrer_cookie_consumed` ## Manual testing 1. Visit `supabase.com/pricing?utm_source=google&utm_medium=cpc` from an external referrer (or use DevTools to set a `Referer` header) 2. Check `_sb_first_referrer` cookie is set in Application > Cookies 3. Navigate to Studio (`supabase.com/dashboard`) 4. In PostHog (or browser network tab), verify the first `$pageview` event has: - `first_referrer_cookie_present: true` - `first_referrer_cookie_consumed: true` - `$utm_source: "google"`, `$utm_medium: "cpc"` - `$referrer` points to the external source, not `supabase.com` 5. Verify subsequent route changes do NOT include `first_referrer_cookie_*` properties ## Review feedback addressed - Added `secure: true` flag on production cookies (Pam's first comment) - Fixed inaccurate JSDoc on `utms` field — keys retain `utm_` prefix (Pam's fourth comment) - Added test coverage for edge cases: malformed URLs, multi-cookie headers, http:// referrers (Pam's sixth comment) - Docs matcher broadening: fast-path exit on cookie-exists check keeps overhead minimal, exclusion list is correct - Extracted shared middleware helper to eliminate duplication across 3 apps - Refactored `handlePageTelemetry` from positional params to options object - Removed redundant null check in `hasPaidSignals` - Added direct-navigation test case - Deleted dead `apps/learn/middleware.ts` - Fixed studio build: integrated cookie stamping into existing `proxy.ts` (Next.js 16 rejects both middleware.ts and proxy.ts) --------- Co-authored-by: pamelachia <26612111+pamelachia@users.noreply.github.com> Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com> |
||
|
|
6bbe2c3297 |
feat(telemetry): add dev telemetry toolbar (#42259)
## Problem We need a local-only UI to inspect client and server telemetry events and override flags during development without touching non-local env behavior. This work is intended to be shared across Studio, Docs, and WWW. ## Changes - Introduced a shared `dev-tools` package with the Dev Telemetry Toolbar UI, trigger, and provider. - Wired the toolbar into Studio, Docs, and WWW app shells (local-only gating). - Added a local-only `devTelemetry()` opt-in with storage gating and SSE subscription. - Wired client PostHog events into a local listener and re-exported types. - Added local flag override cookie support in the UI and CODEOWNERS for the new package. - Added unit tests covering local/non-local behavior and flag utilities. ## Testing Manual (local only): - Start each app locally: `pnpm dev:studio`, `pnpm dev:docs`, `pnpm dev:www` - Open the app, run `devTelemetry()` in the browser console - Click around and confirm both client and server events appear (client will be page views only) - Verify feature flag overrides (PostHog + ConfigCat) persist and restore correctly - Confirm dismissing the toolbar clears local storage and hides the trigger Unblocked by https://github.com/supabase/platform/pull/29172 Resolves GROWTH-591 Demo: [github.com/user-attachments/assets/60b376db-7440-4ada-82f5-d1bd4af4db3b](https://github.com/user-attachments/assets/60b376db-7440-4ada-82f5-d1bd4af4db3b) Screenshots: <img width="1368" height="972" alt="1" src="https://github.com/user-attachments/assets/d2f20a0c-191f-4118-bb5e-15b25f5a54a9" /> <img width="1423" height="790" alt="2" src="https://github.com/user-attachments/assets/115598e2-7287-49bf-9ed7-71ecc679dee3" /> <img width="1433" height="882" alt="3" src="https://github.com/user-attachments/assets/51f666f2-9efc-410f-baec-378bdee9dbfe" /> <img width="608" height="483" alt="4" src="https://github.com/user-attachments/assets/584d6cf5-1b2f-4cee-9e6a-d55ce2e3bae5" /> <img width="628" height="305" alt="5" src="https://github.com/user-attachments/assets/991a9b39-578a-4565-b110-537a02040a53" /> <img width="659" height="447" alt="6" src="https://github.com/user-attachments/assets/95ef405c-fffa-44af-bf6a-f974b780e3fc" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Developer Toolbar (local only): view client/server telemetry, inspect events, and manage/override feature flags with persistent overrides, filtering, and clear/reload. * Client-side telemetry hooks: surface structured events to dev tooling for realtime inspection. * **Bug Fixes** * Fixed end-of-file newline in shared code. * **Chores** * Added dev-tools package, integrated provider and trigger across Studio, Docs, and marketing sites, and added CODEOWNERS entry. * **Tests** * Added comprehensive tests and test setup for the DevToolbar. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Charis Lam <26616127+charislam@users.noreply.github.com> |
||
|
|
1cd1ebfc7f |
chire: Sort imports in all packages, cms, design-system and ui-library apps (#41610)
Sorted all imports in all packages, `cms`, `design-system` and `ui-library` apps by running `pnpm format` on them. All changes in this PR are done by the script. |
||
|
|
f6cb934b36 | fix(telemetry): decouple initial pageview from feature flag loading (#41748) | ||
|
|
b49ad92db3 | feat(telemetry): set gotrue_id as person property in frontend identify (#41750) | ||
|
|
de8e9f6b1b | Fix first-touch referrer for initial $pageview (#41447) | ||
|
|
cf41629249 |
chore: Align profile endpoint usage with api schema corrections (#41430)
* chore: Align profile endpoint usage with api schema corrections * Update schema and remove usage of unused type * No unnecessary export |
||
|
|
71936a69da | fix(telemetry): pass PostHog distinct_id in identify request (#41322) | ||
|
|
654a4b1b7a |
docs: Make it clearer that getting your app approved by Google is all you need to make your Google auth consent screen look better (#40238)
docs: Make it more clear that getting your app approved by Google is enough to make the login screen look better |
||
|
|
99835713d2 |
fix: enable App Router page view tracking on navigation (#40225)
Fixes bug where App Router pages (docs, www/blog) only tracked the initial page load but not subsequent navigations. The issue was introduced in PR #35384 which inverted the logic for App Router telemetry tracking. The condition used a boolean flag that prevented tracking after the initial page view. The root cause: useEffect with [appPathname] dependency fires both on initial mount AND on pathname changes. The flag-based approach couldn't differentiate between these two cases. Solution: Track the previous pathname to detect actual changes. - Initial mount: previousAppPathnameRef is null, skip (initial effect handles it) - Navigation: previousAppPathnameRef !== appPathname, send telemetry Before: Only first page view tracked After: All page navigations tracked (like Pages Router) Affects: docs app, www app (blog pages) |
||
|
|
364f743054 |
Fix PostHog user identification persisting after signout (#40158)
- Add reset() method to PostHogClient class to clear user identification - Call posthogClient.reset() before clearLocalStorage() in signout flow - Include proper error handling and memory leak prevention - Clear all pending state (identification, groups, events) Resolves GROWTH-535 |
||
|
|
8459d18005 |
feat: remove server-side page tracking calls (#38043)
Remove backend API calls for page view and page leave tracking, keeping only client-side PostHog tracking. Generic events and identify calls remain server-side for now. - Remove /platform/telemetry/page API call from handlePageTelemetry - Remove /platform/telemetry/page-leave API call from handlePageLeaveTelemetry - Both functions now return Promise.resolve() for compatibility - Client-side PostHog tracking remains fully functional - Keep sendTelemetryEvent and sendTelemetryIdentify unchanged |
||
|
|
97d746b665 |
fix: resolve 50% session tracking discrepancy on root route (#37853)
* fix: resolve 50% session tracking discrepancy on root route - Fixes race condition causing ~50% discrepancy in session tracking between client and server on root route - Implements event queuing to capture telemetry events before PostHog initializes - Adds session ID correlation to enable unified tracking analysis between client and server events - Uses sendBeacon API for both pageview and pageleave events to ensure reliable capture even during navigation - Adds production safeguards with try/catch blocks and memory caps to prevent API errors from breaking tracking * refactor(posthog-client): reduce max pending events and improve event handling - Decreased the maximum number of queued events from 200 to 20 - Added the use of the sendBeacon API for pending events to survive page unload - Added comments to clarify the handling of pending properties and events during posthog initialization |
||
|
|
e3e8528f72 |
feat: add client-side PostHog telemetry tracking (#37442)
Adds client-side PostHog tracking to run in parallel with server-side telemetry across studio, docs, and www. This enables session replays and resolves a race condition where page views arrive before group assignments resulting in attribution errors. Changes: - Created PostHog client wrapper with consent-aware initialization in common package - Integrated PostHog client calls into existing telemetry functions to send events to both PostHog (client) and backend (server) - Updated CSP to allow connections to PostHog endpoints - Added environment variable support for all apps - PostHog client accepts consent as a parameter and respects user preferences - Events can be distinguished in PostHog by $lib property (posthog-js vs posthog-node) - PostHog URL configured based on environment (staging/local uses ph.supabase.green) - Maintains full backward compatibility with existing telemetry system Resolves GROWTH-438 Resolves GROWTH-271 |
||
|
|
37e44bec9c |
feat: Add GTM (#35567)
* Add third-parties dependency for GTM. Reexport the GTM from the common package. * Add the TelemetryTagManager to four of the production apps. * Add the GOOGLE_TAG_MANAGER_ID env var as a turbo dependency to the 4 apps. * Skip rendering the tag manager if the env var is not set or not running on the platform. * Fix the prop type to be extracted from the component. * Add default values for consent to GTM. * Another try to mimic gtag function. * Fix a link in www. * Try another approach. * try. * Remove the data-redaction flag. * Remove extra code. * Send a sign-up event if GTM is enabled. * Send only the email to GTM. * Minor fixes. * Remove third-parties from pnpm lockfile. * Lets try to make studio work again. * Add CSP rules for img loading for GTM. * Add event for testing. * Add www.googletagmanager.com to the CSP rules. * Add Stape to CSP rules. * Fix stape CSP. * Clean up the code. * Remove extra console.log. * Fix the stape urls for CORS. * Fix the wrong category for Stape URL. * Add google ads urls. * Bump the timeout. * Add google.com to the img-src for google ads. * update csp * remove comment * update to use google analytics without signals * add stape to default-src in csp * move csp to middleware * add google ads support and fix middleware base path * remove google tag manager / google ads references from csp. load via stape proxy instead * add double click url to image src * add Google Tag Manager URL to CSP configuration * add ga4 urls to csp * remove google urls from CSP --------- Co-authored-by: Alaister Young <a@alaisteryoung.com> |
||
|
|
4add928dae |
chore: Update API types (#35879)
* Regenerate all types from develop branch. * Fix all types in studio. * Remove extra type. |
||
|
|
2b419c70a1 |
chore: add usercentrics for consent management (#35384)
* chore: add usercentrics for consent management * client component to make next.js happy * address feedback * move consent state to common * fix import * ensure page events are sent correctly * add feature flag provider to ui library site * fix ui lib 500 error * skip in test env --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> Co-authored-by: Jordi Enric <jordi.err@gmail.com> |
||
|
|
38173acc34 | fix: error when telemetry groups unknown (#35403) | ||
|
|
30b6af4ff3 |
fix (docs): non-platform integrations page (#35285)
There were two bugs when trying to run the integrations page locally with NEXT_PUBLIC_IS_PLATFORM=false: 1. The IS_PLATFORM check imported from common was not evaluating correctly to a boolean. This is because I slapped a 'use client' on the entire common package last year -_-""" which caused all its imports to be evaluated to functions when used in server components. I have now moved the 'use client's down to the submodules that actually need it. 2. When the integrations submenu is empty, the navigation menu errors out because it expects all navigation items to either have children or have links. Have updated this to gracefully hide empty headers. |
||
|
|
6f1cfef213 |
clean circular deps (#34262)
* clean circular deps in telemetry * clean circular deps in command * fix commandmenu circular deps * rm deps.json * fix consent circular dep * fix TOC circular deps * fix wrong import path * fix test types * fix missing fn * undo let change * fix consent component * empty |
||
|
|
30c390c19c |
chore: unify telemetry event sending (#32861)
* chore: unify telemetry event sending * organize some imports * remove final useTelemetryProps * add www telemetry actions typing and docs * remove gaevents * fix build * move telemetry identify into PageTelemetry * fix telemetry constants import --------- Co-authored-by: Pamela Chia <pamelachiamayyee@gmail.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
4577389177 | chore: send feature flags for page events (#32590) |