mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 23:49:03 +00:00
## Problem Studio sends pageview and global crash counters to the frontend metrics endpoint on non-production deployments (#54331), and docs is getting the same in #54424. The marketing site sends neither. ## Solution Port the same implementation to `apps/www`: - **Gate**: the existing `IS_PREVIEW` constant (`NEXT_PUBLIC_VERCEL_ENV === 'preview'`). Nothing is sent in production or local dev. - **Sender**: `lib/frontend-metrics.ts`, the same fire-and-forget `text/plain` POST as Studio, tagged `app: 'www'`. - **Pageview**: `usePageviewMetric` sends one count on hydration and on each pathname change, and skips while the pathname is not yet available. It is mounted once per router: through a small client component in `app/layout.tsx`, and directly in `pages/_app.tsx`. A page is served by only one router, so it is never mounted twice. - **Crash**: `app/global-error.tsx` sends one `global_crash` per error object. `pages/_error.tsx` sends one when the status code is unset or 5xx, so 404s and other 4xx responses are not counted. No CSP change is needed because www does not set a Content-Security-Policy. No turbo change is needed because the www build env already passes `NEXT_PUBLIC_*`. ## Additional context `app/global-error.tsx`, `pages/_error.tsx`, and `lib/frontend-metrics.ts` use relative imports because the `sentry-browser` vitest project, which renders the two error files, has no path-alias resolution. ## Review instructions 1. Open the www preview deployment for this PR with the network tab open. 2. Load an app-router page and a pages-router page. Confirm each sends one POST to the metrics endpoint with `metric_name: "pageview"` and `app: "www"`. 3. Navigate client-side and confirm one more POST per pathname change. 4. In `apps/www`, run `pnpm exec vitest run lib/frontend-metrics.test.ts hooks/usePageviewMetric.test.tsx` and `pnpm exec vitest run --project sentry-browser`.
28 lines
874 B
TypeScript
28 lines
874 B
TypeScript
'use client'
|
|
|
|
import { usePathname } from 'next/navigation'
|
|
import { useEffect, useRef } from 'react'
|
|
|
|
import { IS_PREVIEW } from '@/lib/constants'
|
|
import { sendFrontendMetric } from '@/lib/frontend-metrics'
|
|
|
|
/**
|
|
* Sends one pageview metric on hydration and on every pathname change.
|
|
* Search-param and hash changes are not pageviews. Works in both the app and
|
|
* pages routers.
|
|
*/
|
|
export function usePageviewMetric() {
|
|
const pathname = usePathname()
|
|
const lastSentPathname = useRef<string | null>(null)
|
|
|
|
useEffect(() => {
|
|
if (!IS_PREVIEW) return
|
|
// In the pages router the pathname is null until the router is ready
|
|
if (pathname === null) return
|
|
// Guards against the StrictMode effect double-invoke
|
|
if (lastSentPathname.current === pathname) return
|
|
lastSentPathname.current = pathname
|
|
sendFrontendMetric('pageview')
|
|
}, [pathname])
|
|
}
|