Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flush buffered vitals metrics on page mount #33867

Merged
merged 5 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import measureWebVitals from './performance-relayer'
import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router'
import { getProperError } from '../lib/is-error'
import { trackWebVitalMetric } from './vitals'
import { flushBufferedVitalsMetrics, trackWebVitalMetric } from './vitals'
import { RefreshContext } from './rsc/refresh'

/// <reference types="react-dom/experimental" />
Expand Down Expand Up @@ -1010,7 +1010,10 @@ function Root({
// don't cause any hydration delay:
React.useEffect(() => {
measureWebVitals(onPerfEntry)

flushBufferedVitalsMetrics()
}, [])

return children as React.ReactElement
}

Expand Down
19 changes: 19 additions & 0 deletions packages/next/client/vitals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,19 @@ import { NextWebVitalsMetric } from '../pages/_app'

type ReportWebVitalsCallback = (webVitals: NextWebVitalsMetric) => any
export const webVitalsCallbacks = new Set<ReportWebVitalsCallback>()

let flushed = false
const metrics: NextWebVitalsMetric[] = []

export function getBufferedVitalsMetrics() {
return metrics
}
huozhi marked this conversation as resolved.
Show resolved Hide resolved

export function flushBufferedVitalsMetrics() {
flushed = true
metrics.length = 0
}

export function trackWebVitalMetric(metric: NextWebVitalsMetric) {
metrics.push(metric)
webVitalsCallbacks.forEach((callback) => callback(metric))
Expand All @@ -13,6 +24,14 @@ export function trackWebVitalMetric(metric: NextWebVitalsMetric) {
export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
const metricIndexRef = useRef(0)

if (process.env.NODE_ENV === 'development') {
if (flushed) {
console.error(
'The `useWebVitalsReport` hook was called too late -- did you use it inside of a <Suspense> boundary?'
)
}
}

useEffect(() => {
// Flush calculated metrics
const reportMetric = (metric: NextWebVitalsMetric) => {
Expand Down
3 changes: 3 additions & 0 deletions test/integration/relay-analytics-disabled/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getBufferedVitalsMetrics } from 'next/dist/client/vitals'

if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []

Expand All @@ -20,6 +22,7 @@ export default () => {
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
<p>{`buffered metrics: ${getBufferedVitalsMetrics().length}`}</p>
</div>
)
}
2 changes: 2 additions & 0 deletions test/integration/relay-analytics-disabled/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,13 @@ describe('Analytics relayer (disabled)', () => {
const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('h1')
const h1Text = await browser.elementByCss('h1').text()
const pText = await browser.elementByCss('p').text()
const firstContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("FCP")')
)

expect(h1Text).toMatch(/Foo!/)
expect(pText).toMatch('buffered metrics: 0')

expect(firstContentfulPaint).not.toBeNaN()
expect(firstContentfulPaint).toBeGreaterThan(0)
Expand Down
2 changes: 2 additions & 0 deletions test/integration/relay-analytics/pages/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* global localStorage */
import { unstable_useWebVitalsReport } from 'next/vitals'
import { getBufferedVitalsMetrics } from 'next/dist/client/vitals'

if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []
Expand Down Expand Up @@ -37,6 +38,7 @@ export default () => {
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
<p>{`buffered metrics: ${getBufferedVitalsMetrics().length}`}</p>
</div>
)
}
2 changes: 2 additions & 0 deletions test/integration/relay-analytics/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ function runTest() {
await browser.waitForElementByCss('h1')

const h1Text = await browser.elementByCss('h1').text()
const pText = await browser.elementByCss('p').text()
const data = parseFloat(
await browser.eval('localStorage.getItem("Next.js-hydration")')
)
Expand All @@ -81,6 +82,7 @@ function runTest() {
)
let cls = await browser.eval('localStorage.getItem("CLS")')
expect(h1Text).toMatch(/Foo!/)
expect(pText).toMatch('buffered metrics: 0')
expect(data).not.toBeNaN()
expect(data).toBeGreaterThan(0)
expect(firstByte).not.toBeNaN()
Expand Down