Skip to content

Commit

Permalink
Flush buffered vitals metrics on page mount (#33867)
Browse files Browse the repository at this point in the history
## Bug

fixes #32631

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
  • Loading branch information
huozhi committed Feb 1, 2022
1 parent dd48660 commit 4786557
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/next/client/index.tsx
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
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
}

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
@@ -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
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
@@ -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
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

0 comments on commit 4786557

Please sign in to comment.