Unverified Commit 92edfb95 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Cont. Update performance relayer and remove unstable prefix (#12665)

* updates relayer, uses web-vital lib, removes fid polyfill and removes unstable prefix from relayer

* simplify logic, fix null check

* update docs

* Update tests

* Rename relayWebVitals to reportWebVitals
Co-authored-by: 's avatarhousseindjirdeh <houssein@google.com>
parent ff486914
---
description: Measure and track page performance using Next.js's build-in performance relayer
---
# Measuring performance
Next.js has a built-in relayer that allows you to analyze and measure the performance of
pages using different metrics.
To measure any of the supported metrics, you will need to create a [custom
App](/docs/advanced-features/custom-app.md) component and define a `reportWebVitals` function:
```js
import App from 'next/app'
export default MyApp
export function reportWebVitals(metric) {
console.log(metric)
}
```
This function is fired when the final values for any of the metrics have finished calculating on
the page. You can use to log any of the results to the console or send to a particular endpoint.
The `metric` object returned to the function consists of a number of properties:
- `id`: Unique identifier for the metric in the context of the current page load
- `name`: Metric name
- `startTime`: First recorded timestamp of the performance entry (if applicable)
- `value`: Value, or duration, of performance entry
- `label`: Type of metric (`web-vital` or `custom`)
There are two types of metrics that are tracked:
- Web Vitals
- Custom metrics
## Web Vitals
[Web Vitals](https://web.dev/vitals/) are a set of useful metrics that aim to capture the user
experience of a web page. The following web vitals are all included:
- [Time to First Byte](https://developer.mozilla.org/en-US/docs/Glossary/Time_to_first_byte) (TTFB)
- [First Contentful Paint](https://developer.mozilla.org/en-US/docs/Glossary/First_contentful_paint) (FCP)
- [Largest Contentful Paint](https://web.dev/lcp/) (LCP)
- [First Input Delay](https://web.dev/fid/) (FID)
- [Cumulative Layout Shift](https://web.dev/cls/) (CLS)
You can handle all the results of these metrics using the `web-vital` label:
```js
export function reportWebVitals(metric) {
if (metric.label === 'web-vital') {
console.log(metric) // The metric object ({ id, name, startTime, value, label }) is logged to the console
}
}
```
There's also the option of handling each of the metrics separately:
```js
export function reportWebVitals(metric) {
switch (metric.name) {
case 'FCP':
// handle FCP results
break
case 'LCP':
// handle LCP results
break
case 'CLS':
// handle CLS results
break
case 'FID':
// handle FID results
break
case 'TTFB':
// handle TTFB results
break
default:
break
}
}
```
A third-party library, [web-vitals](https://github.com/GoogleChrome/web-vitals), is used to measure
these metrics. Browser compatibility depends on the particular metric, so refer to the [Browser
Support](https://github.com/GoogleChrome/web-vitals#browser-support) section to find out which
browsers are supported.
## Custom metrics
In addition to the core metrics listed above, there are some additional custom metrics that
measure the time it takes for the page to hydrate and render:
- `Next.js-hydration`: Length of time it takes for the page to start and finish hydrating (in ms)
- `Next.js-route-change-to-render`: Length of time it takes for a page to start rendering after a
route change (in ms)
- `Next.js-render`: Length of time it takes for a page to finish render after a route change (in ms)
You can handle all the results of these metrics using the `custom` label:
```js
export function reportWebVitals(metric) {
if (metric.label === 'custom') {
console.log(metric) // The metric object ({ id, name, startTime, value, label }) is logged to the console
}
}
```
There's also the option of handling each of the metrics separately:
```js
export function reportWebVitals(metric) {
switch (metric.name) {
case 'Next.js-hydration':
// handle hydration results
break
case 'Next.js-route-change-to-render':
// handle route-change to render results
break
case 'Next.js-render':
// handle render results
break
default:
break
}
}
```
These metrics work in all browsers that support the [User Timing API](https://caniuse.com/#feat=user-timing).
## Sending results to analytics
With the relay function, you can send any of results to an analytics endpoint to measure and track
real user performance on your site. For example:
```js
export function reportWebVitals(metric) {
const body = JSON.stringify(metric)
const url = 'https://example.com/analytics'
// Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
;(navigator.sendBeacon && navigator.sendBeacon(url, body)) ||
fetch(url, { body, method: 'POST', keepalive: true })
}
```
> **Note**: If you use [Google Analytics](https://analytics.google.com/analytics/web/), using the
> `id` value can allow you to construct metric distributions manually (to calculate percentiles,
> etc...).
>
> ```js
> export function reportWebVitals({ id, name, label, value }) {
> ga('send', 'event', {
> eventCategory: `Next.js ${ label } metric`,
> eventAction: name,
> eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
> eventLabel: id, // id unique to current page load
> nonInteraction: true, // avoids affecting bounce rate.
> },
> }
> ```
>
> Read more about sending results to Google Analytics [here](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics).
...@@ -156,6 +156,10 @@ ...@@ -156,6 +156,10 @@
{ {
"title": "Multi Zones", "title": "Multi Zones",
"path": "/docs/advanced-features/multi-zones.md" "path": "/docs/advanced-features/multi-zones.md"
},
{
"title": "Measuring performance",
"path": "/docs/advanced-features/measuring-performance.md"
} }
] ]
}, },
......
...@@ -844,9 +844,6 @@ export default async function getBaseWebpackConfig( ...@@ -844,9 +844,6 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify( 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(
config.experimental.basePath config.experimental.basePath
), ),
'process.env.__NEXT_FID_POLYFILL': JSON.stringify(
config.experimental.measureFid
),
'process.env.__NEXT_FAST_REFRESH': JSON.stringify(hasReactRefresh), 'process.env.__NEXT_FAST_REFRESH': JSON.stringify(hasReactRefresh),
...(isServer ...(isServer
? { ? {
......
...@@ -11,11 +11,7 @@ import * as envConfig from '../next-server/lib/runtime-config' ...@@ -11,11 +11,7 @@ import * as envConfig from '../next-server/lib/runtime-config'
import { getURL, loadGetInitialProps, ST } from '../next-server/lib/utils' import { getURL, loadGetInitialProps, ST } from '../next-server/lib/utils'
import initHeadManager from './head-manager' import initHeadManager from './head-manager'
import PageLoader from './page-loader' import PageLoader from './page-loader'
import { import measureWebVitals from './performance-relayer'
observeLargestContentfulPaint,
observeLayoutShift,
observePaint,
} from './performance-relayer'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -176,14 +172,35 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => { ...@@ -176,14 +172,35 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
} }
const { page: app, mod } = await pageLoader.loadPageScript('/_app') const { page: app, mod } = await pageLoader.loadPageScript('/_app')
App = app App = app
if (mod && mod.unstable_onPerformanceData) {
onPerfEntry = function({ name, startTime, value, duration, entryType }) { if (mod && mod.reportWebVitals) {
mod.unstable_onPerformanceData({ onPerfEntry = ({
id,
name,
startTime,
value,
duration,
entryType,
entries,
}) => {
// Combines timestamp with random number for unique ID
const uniqueID = `${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) +
1e12}`
let perfStartEntry
if (entries && entries.length) {
perfStartEntry = entries[0].startTime
}
mod.reportWebVitals({
id: id || uniqueID,
name, name,
startTime, startTime: startTime || perfStartEntry,
value, value: value == null ? duration : value,
duration, label:
entryType, entryType === 'mark' || entryType === 'measure'
? 'custom'
: 'web-vital',
}) })
} }
} }
...@@ -368,22 +385,14 @@ function renderReactElement(reactEl, domEl) { ...@@ -368,22 +385,14 @@ function renderReactElement(reactEl, domEl) {
if (isInitialRender) { if (isInitialRender) {
ReactDOM.hydrate(reactEl, domEl, markHydrateComplete) ReactDOM.hydrate(reactEl, domEl, markHydrateComplete)
isInitialRender = false isInitialRender = false
if (onPerfEntry && ST) {
measureWebVitals(onPerfEntry)
}
} else { } else {
ReactDOM.render(reactEl, domEl, markRenderComplete) ReactDOM.render(reactEl, domEl, markRenderComplete)
} }
} }
if (onPerfEntry && ST) {
try {
observeLayoutShift(onPerfEntry)
observeLargestContentfulPaint(onPerfEntry)
observePaint(onPerfEntry)
} catch (e) {
window.addEventListener('load', () => {
performance.getEntriesByType('paint').forEach(onPerfEntry)
})
}
}
} }
function markHydrateComplete() { function markHydrateComplete() {
...@@ -399,18 +408,7 @@ function markHydrateComplete() { ...@@ -399,18 +408,7 @@ function markHydrateComplete() {
performance.measure('Next.js-hydration', 'beforeRender', 'afterHydrate') performance.measure('Next.js-hydration', 'beforeRender', 'afterHydrate')
if (onPerfEntry) { if (onPerfEntry) {
if (process.env.__NEXT_FID_POLYFILL) {
import('../next-server/lib/fid-measure')
.then(mod => {
mod.default(onPerfEntry)
})
.catch(err => {
console.error('Error measuring First Input Delay', err)
})
}
performance.getEntriesByName('Next.js-hydration').forEach(onPerfEntry) performance.getEntriesByName('Next.js-hydration').forEach(onPerfEntry)
performance.getEntriesByName('beforeRender').forEach(onPerfEntry)
} }
clearMarks() clearMarks()
} }
......
function isTypeSupported(type) { import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
if (self.PerformanceObserver && PerformanceObserver.supportedEntryTypes) {
return PerformanceObserver.supportedEntryTypes.includes(type) export default onPerfEntry => {
} getCLS(onPerfEntry)
return false getFID(onPerfEntry)
} getFCP(onPerfEntry)
getLCP(onPerfEntry)
export function observeLayoutShift(onPerfEntry) { getTTFB(onPerfEntry)
if (isTypeSupported('layout-shift')) {
let cumulativeScore = 0
const observer = new PerformanceObserver(list => {
for (const entry of list.getEntries()) {
// Only count layout shifts without recent user input.
if (!entry.hadRecentInput) {
cumulativeScore += entry.value
}
}
})
observer.observe({ type: 'layout-shift', buffered: true })
document.addEventListener(
'visibilitychange',
function clsObserver() {
if (document.visibilityState === 'hidden') {
// Force any pending records to be dispatched.
observer.takeRecords()
observer.disconnect()
document.removeEventListener('visibilitychange', clsObserver, true)
onPerfEntry({
name: 'cumulative-layout-shift',
value: cumulativeScore,
})
}
},
true
)
}
}
export function observeLargestContentfulPaint(onPerfEntry) {
if (isTypeSupported('largest-contentful-paint')) {
// Create a variable to hold the latest LCP value (since it can change).
let lcp
// Create the PerformanceObserver instance.
const observer = new PerformanceObserver(entryList => {
const entries = entryList.getEntries()
const lastEntry = entries[entries.length - 1]
lcp = lastEntry.renderTime || lastEntry.loadTime
})
observer.observe({ type: 'largest-contentful-paint', buffered: true })
document.addEventListener(
'visibilitychange',
function lcpObserver() {
if (lcp && document.visibilityState === 'hidden') {
document.removeEventListener('visibilitychange', lcpObserver, true)
onPerfEntry({
name: 'largest-contentful-paint',
value: lcp,
})
}
},
true
)
}
}
export function observePaint(onPerfEntry) {
const observer = new PerformanceObserver(list => {
list.getEntries().forEach(onPerfEntry)
})
observer.observe({
type: 'paint',
buffered: true,
})
} }
/* global hydrationMetrics */
export default onPerfEntry => {
hydrationMetrics.onInputDelay((delay, event) => {
const hydrationMeasures = performance.getEntriesByName(
'Next.js-hydration',
'measure'
)
if (hydrationMeasures.length > 0) {
const { startTime, duration } = hydrationMeasures[0]
const hydrateEnd = startTime + duration
if (event.timeStamp > hydrateEnd) {
onPerfEntry({
name: 'first-input-delay-after-hydration',
startTime: event.timeStamp,
duration: delay,
})
} else {
onPerfEntry({
name: 'first-input-delay-before-hydration',
startTime: event.timeStamp,
duration: delay,
})
}
}
})
}
/**
* This is a modified version of the First Input Delay polyfill
* https://github.com/GoogleChromeLabs/first-input-delay
*
* It checks for a first input before and after hydration
*/
type DelayCallback = (delay: number, event: Event) => void
type addEventListener = (
type: string,
listener: EventListener,
listenerOpts: EventListenerOptions
) => void
type removeEventListener = addEventListener
function fidPolyfill(
addEventListener: addEventListener,
removeEventListener: removeEventListener
) {
var firstInputEvent: Event
var firstInputDelay: number
var firstInputTimeStamp: number
var callbacks: DelayCallback[] = []
var listenerOpts = { passive: true, capture: true }
var startTimeStamp = +new Date()
var pointerup = 'pointerup'
var pointercancel = 'pointercancel'
function onInputDelay(callback: DelayCallback) {
callbacks.push(callback)
reportInputDelayIfRecordedAndValid()
}
function recordInputDelay(delay: number, evt: Event) {
firstInputEvent = evt
firstInputDelay = delay
firstInputTimeStamp = +new Date()
reportInputDelayIfRecordedAndValid()
}
function reportInputDelayIfRecordedAndValid() {
var hydrationMeasures = performance.getEntriesByName(
'Next.js-hydration',
'measure'
)
var firstInputStart = firstInputTimeStamp - startTimeStamp
if (
firstInputDelay >= 0 &&
firstInputDelay < firstInputStart &&
(hydrationMeasures.length === 0 ||
hydrationMeasures[0].startTime < firstInputStart)
) {
callbacks.forEach(function(callback) {
callback(firstInputDelay, firstInputEvent)
})
// If the app is already hydrated, that means the first "post-hydration" input
// has been measured and listeners can be removed
if (hydrationMeasures.length > 0) {
eachEventType(removeEventListener)
callbacks = []
}
}
}
function onPointerDown(delay: number, evt: Event) {
function onPointerUp() {
recordInputDelay(delay, evt)
}
function onPointerCancel() {
removePointerEventListeners()
}
function removePointerEventListeners() {
removeEventListener(pointerup, onPointerUp, listenerOpts)
removeEventListener(pointercancel, onPointerCancel, listenerOpts)
}
addEventListener(pointerup, onPointerUp, listenerOpts)
addEventListener(pointercancel, onPointerCancel, listenerOpts)
}
function onInput(evt: Event) {
if (evt.cancelable) {
var isEpochTime = evt.timeStamp > 1e12
var now = isEpochTime ? +new Date() : performance.now()
var delay = now - evt.timeStamp
if (evt.type === 'pointerdown') {
onPointerDown(delay, evt)
} else {
recordInputDelay(delay, evt)
}
}
}
function eachEventType(callback: addEventListener | removeEventListener) {
var eventTypes = [
'click',
'mousedown',
'keydown',
'touchstart',
'pointerdown',
]
eventTypes.forEach(function(eventType) {
callback(eventType, onInput, listenerOpts)
})
}
eachEventType(addEventListener)
var context = self as any
context['hydrationMetrics'] = context['hydrationMetrics'] || {}
context['hydrationMetrics']['onInputDelay'] = onInputDelay
}
export default fidPolyfill
...@@ -52,7 +52,6 @@ const defaultConfig: { [key: string]: any } = { ...@@ -52,7 +52,6 @@ const defaultConfig: { [key: string]: any } = {
basePath: '', basePath: '',
sassOptions: {}, sassOptions: {},
pageEnv: false, pageEnv: false,
measureFid: false,
reactRefresh: false, reactRefresh: false,
}, },
future: { future: {
......
...@@ -105,6 +105,7 @@ ...@@ -105,6 +105,7 @@
"styled-jsx": "3.2.5", "styled-jsx": "3.2.5",
"use-subscription": "1.1.1", "use-subscription": "1.1.1",
"watchpack": "2.0.0-beta.13", "watchpack": "2.0.0-beta.13",
"web-vitals": "0.2.1",
"webpack": "4.43.0", "webpack": "4.43.0",
"webpack-sources": "1.4.3" "webpack-sources": "1.4.3"
}, },
......
...@@ -13,7 +13,6 @@ import { ...@@ -13,7 +13,6 @@ import {
DocumentInitialProps, DocumentInitialProps,
DocumentProps, DocumentProps,
} from '../next-server/lib/utils' } from '../next-server/lib/utils'
import fidPolyfill from '../next-server/lib/fid'
import { cleanAmpPath } from '../next-server/server/utils' import { cleanAmpPath } from '../next-server/server/utils'
import { htmlEscapeJsonString } from '../server/htmlescape' import { htmlEscapeJsonString } from '../server/htmlescape'
...@@ -277,20 +276,6 @@ export class Head extends Component< ...@@ -277,20 +276,6 @@ export class Head extends Component<
)) ))
} }
getFidPolyfill(): JSX.Element | null {
if (!process.env.__NEXT_FID_POLYFILL) {
return null
}
return (
<script
dangerouslySetInnerHTML={{
__html: `(${fidPolyfill})(addEventListener, removeEventListener)`,
}}
/>
)
}
render() { render() {
const { const {
styles, styles,
...@@ -528,7 +513,6 @@ export class Head extends Component< ...@@ -528,7 +513,6 @@ export class Head extends Component<
{styles || null} {styles || null}
</> </>
)} )}
{!disableRuntimeJS && this.getFidPolyfill()}
{React.createElement(React.Fragment, {}, ...(headTags || []))} {React.createElement(React.Fragment, {}, ...(headTags || []))}
</head> </head>
) )
......
...@@ -7,7 +7,7 @@ export default class MyApp extends App {} ...@@ -7,7 +7,7 @@ export default class MyApp extends App {}
/* /*
Method is experimental and will eventually be handled in a Next.js plugin Method is experimental and will eventually be handled in a Next.js plugin
*/ */
export function unstable_onPerformanceData(data) { export function reportWebVitals(data) {
localStorage.setItem( localStorage.setItem(
data.name || data.entryType, data.name || data.entryType,
data.value !== undefined ? data.value : data.startTime data.value !== undefined ? data.value : data.startTime
......
...@@ -24,23 +24,21 @@ describe('Analytics relayer', () => { ...@@ -24,23 +24,21 @@ describe('Analytics relayer', () => {
const data = parseFloat( const data = parseFloat(
await browser.eval('localStorage.getItem("Next.js-hydration")') await browser.eval('localStorage.getItem("Next.js-hydration")')
) )
const firstPaint = parseFloat( const firstByte = parseFloat(
await browser.eval('localStorage.getItem("first-paint")') await browser.eval('localStorage.getItem("TTFB")')
) )
const firstContentfulPaint = parseFloat( const firstContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("first-contentful-paint")') await browser.eval('localStorage.getItem("FCP")')
) )
let largestContentfulPaint = await browser.eval( let largestContentfulPaint = await browser.eval(
'localStorage.getItem("largest-contentful-paint")' 'localStorage.getItem("LCP")'
)
let cls = await browser.eval(
'localStorage.getItem("cumulative-layout-shift")'
) )
let cls = await browser.eval('localStorage.getItem("CLS")')
expect(h1Text).toMatch(/Foo!/) expect(h1Text).toMatch(/Foo!/)
expect(data).not.toBeNaN() expect(data).not.toBeNaN()
expect(data).toBeGreaterThan(0) expect(data).toBeGreaterThan(0)
expect(firstPaint).not.toBeNaN() expect(firstByte).not.toBeNaN()
expect(firstPaint).toBeGreaterThan(0) expect(firstByte).toBeGreaterThan(0)
expect(firstContentfulPaint).not.toBeNaN() expect(firstContentfulPaint).not.toBeNaN()
expect(firstContentfulPaint).toBeGreaterThan(0) expect(firstContentfulPaint).toBeGreaterThan(0)
expect(largestContentfulPaint).toBeNull() expect(largestContentfulPaint).toBeNull()
...@@ -50,11 +48,9 @@ describe('Analytics relayer', () => { ...@@ -50,11 +48,9 @@ describe('Analytics relayer', () => {
await browser.refresh() await browser.refresh()
await browser.waitForElementByCss('h1') await browser.waitForElementByCss('h1')
largestContentfulPaint = parseFloat( largestContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("largest-contentful-paint")') await browser.eval('localStorage.getItem("LCP")')
)
cls = parseFloat(
await browser.eval('localStorage.getItem("cumulative-layout-shift")')
) )
cls = parseFloat(await browser.eval('localStorage.getItem("CLS")'))
expect(cls).not.toBeNull() expect(cls).not.toBeNull()
expect(largestContentfulPaint).not.toBeNaN() expect(largestContentfulPaint).not.toBeNaN()
expect(largestContentfulPaint).toBeGreaterThan(0) expect(largestContentfulPaint).toBeGreaterThan(0)
......
...@@ -80,7 +80,7 @@ describe('Production response size', () => { ...@@ -80,7 +80,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 262 * 1024 const delta = responseSizesBytes - 263 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
...@@ -100,7 +100,7 @@ describe('Production response size', () => { ...@@ -100,7 +100,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 166 * 1024 const delta = responseSizesBytes - 168 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
...@@ -17274,6 +17274,11 @@ wcwidth@^1.0.0, wcwidth@^1.0.1: ...@@ -17274,6 +17274,11 @@ wcwidth@^1.0.0, wcwidth@^1.0.1:
dependencies: dependencies:
defaults "^1.0.3" defaults "^1.0.3"
web-vitals@0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/web-vitals/-/web-vitals-0.2.1.tgz#60782fa690243fe35613759a0c26431f57ba7b2d"
integrity sha512-2pdRlp6gJpOCg0oMMqwFF0axjk5D9WInc09RSYtqFgPXQ15+YKNQ7YnBBEqAL5jvmfH9WvoXDMb8DHwux7pIew==
webidl-conversions@^4.0.2: webidl-conversions@^4.0.2:
version "4.0.2" version "4.0.2"
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-4.0.2.tgz#a855980b1f0b6b359ba1d5d9fb39ae941faa63ad"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment