Files
supabase/apps/docs/lib/frontend-metrics.test.ts
Charis 34e0361708 feat(docs): send pageview and global crash metrics on preview (#54424)
## Problem

Studio sends pageview and global crash counters to the frontend metrics
endpoint on non-production deployments (#54331). Docs sends neither, so
there is no equivalent signal for docs previews.

## Solution

Port the Studio implementation to `apps/docs`:

- **Gate**: new `IS_PREVIEW` constant, true only on Vercel preview
deployments of the hosted platform. It is false in production, local
dev, self-hosted, and the Nimbus flavor. Docs has no long-running
staging environment, so there is no staging branch in the gate.
- **Sender**: `lib/frontend-metrics.ts`, the same fire-and-forget
`text/plain` POST as Studio, tagged `app: 'docs'`.
- **Pageview**: `usePageviewMetric` sends one count on hydration and on
each pathname change. It is mounted from the root layout through a small
client component.
- **Crash**: `app/error.tsx` and `app/global-error.tsx` each send one
`global_crash`. A given error reaches only one of the two boundaries,
and a `WeakSet` counts each error object once, so effect re-runs do not
double count.
- **Nimbus**: docs had no client-readable Nimbus check, so the gate
reads `NEXT_PUBLIC_IS_NIMBUS` (same name and semantics as Studio) and
the variable is added to the docs build env in `turbo.jsonc`.

No CSP change is needed because docs does not set a
Content-Security-Policy.

## Additional context

`NEXT_PUBLIC_IS_NIMBUS` must be set on the Nimbus docs project for the
Nimbus exclusion to take effect. The metrics also require
`NEXT_PUBLIC_IS_PLATFORM=true` on preview deployments.

## Review instructions

1. Open the docs preview deployment for this PR with the network tab
open.
2. Load any page and confirm one POST to the metrics endpoint with
`metric_name: "pageview"` and `app: "docs"`.
3. Navigate to another page client-side and confirm one more POST.
Changing only the hash or search params should not send one.
4. Run `pnpm -F docs exec vitest run lib/frontend-metrics.test.ts
hooks/usePageviewMetric.test.tsx`.
2026-12-01 12:01:27 -05:00

111 lines
3.0 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { reportGlobalCrashMetric, sendFrontendMetric } from './frontend-metrics'
const mocks = vi.hoisted(() => ({ isEnabled: true }))
vi.mock('@/lib/constants', () => ({
get IS_PREVIEW() {
return mocks.isEnabled
},
}))
describe('sendFrontendMetric', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it.each(['pageview', 'global_crash'] as const)(
'posts a single %s event as a CORS-simple request',
(metricName) => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)
sendFrontendMetric(metricName)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('https://misc-functions.vercel.app/api/metrics')
expect(init).toMatchObject({
method: 'POST',
keepalive: true,
credentials: 'omit',
headers: { 'Content-Type': 'text/plain' },
})
expect(JSON.parse(init.body)).toEqual({
environment: 'staging',
events: [{ metric_name: metricName, value: 1, metadata: { app: 'docs' } }],
})
}
)
it('does not throw or leave an unhandled rejection when the request fails', async () => {
const unhandled = vi.fn()
process.on('unhandledRejection', unhandled)
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
expect(() => sendFrontendMetric('global_crash')).not.toThrow()
await new Promise((resolve) => setImmediate(resolve))
process.off('unhandledRejection', unhandled)
expect(unhandled).not.toHaveBeenCalled()
})
it('does not throw when fetch throws synchronously', () => {
vi.stubGlobal(
'fetch',
vi.fn(() => {
throw new Error('boom')
})
)
expect(() => sendFrontendMetric('global_crash')).not.toThrow()
})
})
describe('reportGlobalCrashMetric', () => {
const fetchMock = vi.fn()
beforeEach(() => {
mocks.isEnabled = true
fetchMock.mockReset().mockResolvedValue(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('sends one global_crash metric', () => {
reportGlobalCrashMetric(new Error('boom'))
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(JSON.parse(fetchMock.mock.calls[0][1].body).events[0].metric_name).toBe('global_crash')
})
it('sends nothing when the gate is off', () => {
mocks.isEnabled = false
reportGlobalCrashMetric(new Error('boom'))
expect(fetchMock).not.toHaveBeenCalled()
})
it('counts the same error object once', () => {
const error = new Error('boom')
reportGlobalCrashMetric(error)
reportGlobalCrashMetric(error)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('counts non-object errors each time', () => {
reportGlobalCrashMetric('boom')
reportGlobalCrashMetric('boom')
reportGlobalCrashMetric(undefined)
expect(fetchMock).toHaveBeenCalledTimes(3)
})
})