Files
supabase/apps/studio/lib/frontend-metrics.ts
Charis 975689dcfc feat(studio): send pageview and global crash metrics on staging and preview (#54331)
## Problem

We need simple counts of every pageview and every global crash for SLO
monitoring. These counts need to go to observability ingest, not to
Sentry, etc., so they can be part of our Grafana dashboards pipeline.

## Solution

- `usePageviewMetric` sends one `pageview` event on first load
(hydration) and on every client-side navigation that changes the
pathname. Changes to only the query string or hash do not count.
- A `global_crash` event is sent once when the global crash screen is
shown. That covers both the root `ErrorBoundary` and the root route
`errorComponent`. Chunk-load errors that are recovered by an automatic
reload are not counted, which matches what is reported to Sentry.
- Both are gated by a new `IS_STAGING_OR_PREVIEW` constant. It is false
on production, local development, self-hosted and Nimbus.
- The request is a fire-and-forget `fetch` with `keepalive: true` and
`credentials: 'omit'`. It uses a `text/plain` body, so there is no CORS
preflight. Errors are swallowed.
- The endpoint origin is added to `connect-src` for all platform
environments, because production will need it later. No other CSP
directive changes.

## Review instructions

1. Open the Studio preview deployment for this PR with the network panel
open.
2. Load any page. See one `POST /api/metrics` request that returns 204.
3. Navigate to another page. See one more request.
4. Change only a query parameter (for example a table filter). See no
new request.

## Checklist

Check all before review:

- [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)
2026-12-01 15:35:05 +01:00

25 lines
794 B
TypeScript

const METRICS_ENDPOINT = 'https://misc-functions.vercel.app/api/metrics'
type FrontendMetricName = 'pageview' | 'global_crash'
/**
* Fire-and-forget frontend metric. Sent as text/plain so the request stays
* CORS-simple (no preflight). Failures are intentionally swallowed.
*/
export function sendFrontendMetric(metricName: FrontendMetricName): void {
try {
fetch(METRICS_ENDPOINT, {
method: 'POST',
keepalive: true,
credentials: 'omit',
headers: { 'Content-Type': 'text/plain' },
body: JSON.stringify({
environment: 'staging',
events: [{ metric_name: metricName, value: 1, metadata: { app: 'studio' } }],
}),
}).catch(() => {})
} catch {
// fetch can throw synchronously (e.g. invalid arguments); never surface it
}
}