Unverified Commit fb4c4988 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Upgrade web-vitals to v6 and report soft navigations (#97232)

## Summary

Upgrades the vendored `web-vitals` dependency to v6.0.1 and enables
soft-navigation reporting for CLS, INP, and LCP. This lets
`useReportWebVitals` report metrics against the navigation where they
occurred, including `navigationURL` for route attribution.

The upgrade also removes the obsolete FID integration and compatibility
patch, regenerates the standard and attribution bundles, and updates the
public metric types and documentation to match the current upstream API.

Related to #97161.

## Verification

- Added production-mode coverage for initial and soft-navigation Web
Vitals reporting with both Turbopack and Webpack.

<!-- NEXT_JS_LLM -->
parent 83eabc8f
...@@ -88,7 +88,6 @@ experience of a web page. The following web vitals are all included: ...@@ -88,7 +88,6 @@ experience of a web page. The following web vitals are all included:
- [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB) - [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB)
- [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP) - [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP)
- [Largest Contentful Paint](https://web.dev/lcp/) (LCP) - [Largest Contentful Paint](https://web.dev/lcp/) (LCP)
- [First Input Delay](https://web.dev/fid/) (FID)
- [Cumulative Layout Shift](https://web.dev/cls/) (CLS) - [Cumulative Layout Shift](https://web.dev/cls/) (CLS)
- [Interaction to Next Paint](https://web.dev/inp/) (INP) - [Interaction to Next Paint](https://web.dev/inp/) (INP)
......
...@@ -69,10 +69,14 @@ export default function Layout({ children }) { ...@@ -69,10 +69,14 @@ export default function Layout({ children }) {
The `metric` object passed as the hook's argument consists of a number of properties: The `metric` object passed as the hook's argument consists of a number of properties:
- `id`: Unique identifier for the metric in the context of the current page load - `id`: Unique identifier for the metric in the context of the current page load
- `name`: The name of the performance metric. Possible values include names of [Web Vitals](#web-vitals) metrics (TTFB, FCP, LCP, FID, CLS) specific to a web application. - `name`: The name of the performance metric. Possible values include names of [Web Vitals](#web-vitals) metrics (TTFB, FCP, LCP, INP, CLS) specific to a web application.
- `delta`: The difference between the current value and the previous value of the metric. The value is typically in milliseconds and represents the change in the metric's value over time. - `delta`: The difference between the current value and the previous value of the metric. The value is typically in milliseconds and represents the change in the metric's value over time.
- `entries`: An array of [Performance Entries](https://developer.mozilla.org/docs/Web/API/PerformanceEntry) associated with the metric. These entries provide detailed information about the performance events related to the metric. - `entries`: An array of [Performance Entries](https://developer.mozilla.org/docs/Web/API/PerformanceEntry) associated with the metric. These entries provide detailed information about the performance events related to the metric.
- `navigationType`: Indicates the navigation type that triggered metric collection. Values are derived from [PerformanceNavigationTiming.type](https://developer.mozilla.org/docs/Web/API/PerformanceNavigationTiming/type) and may include `"navigate"`, `"reload"`, `"prerender"`, `"back-forward"` (normalized from `"back_forward"`), `"back-forward-cache"` (BFCache restore), and `"restore"` (page restored after discard). - `navigationType`: Indicates the navigation type that triggered metric collection. Values are derived from [PerformanceNavigationTiming.type](https://developer.mozilla.org/docs/Web/API/PerformanceNavigationTiming/type) and may include `"navigate"`, `"reload"`, `"prerender"`, `"back-forward"` (normalized from `"back_forward"`), `"back-forward-cache"` (BFCache restore), `"restore"` (page restored after discard), and `"soft-navigation"`.
- `navigationId`: The ID of the navigation for which the metric was measured.
- `navigationURL`: The URL of the navigation for which the metric was measured. This is especially useful for soft navigations because a metric may be reported after the URL has changed again.
- `navigationStartTime`: The start time of the navigation for which the metric was measured.
- `navigationInteractionId`: For soft navigations, the interaction ID that triggered the navigation.
- `rating`: A qualitative rating of the metric value, providing an assessment of the performance. Possible values are `"good"`, `"needs-improvement"`, and `"poor"`. The rating is typically determined by comparing the metric value against predefined thresholds that indicate acceptable or suboptimal performance. - `rating`: A qualitative rating of the metric value, providing an assessment of the performance. Possible values are `"good"`, `"needs-improvement"`, and `"poor"`. The rating is typically determined by comparing the metric value against predefined thresholds that indicate acceptable or suboptimal performance.
- `value`: The actual value or duration of the performance entry, typically in milliseconds. The value provides a quantitative measure of the performance aspect being tracked by the metric. The source of the value depends on the specific metric being measured and can come from various [Performance API](https://developer.mozilla.org/docs/Web/API/Performance_API)s. - `value`: The actual value or duration of the performance entry, typically in milliseconds. The value provides a quantitative measure of the performance aspect being tracked by the metric. The source of the value depends on the specific metric being measured and can come from various [Performance API](https://developer.mozilla.org/docs/Web/API/Performance_API)s.
...@@ -84,7 +88,6 @@ experience of a web page. The following web vitals are all included: ...@@ -84,7 +88,6 @@ experience of a web page. The following web vitals are all included:
- [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB) - [Time to First Byte](https://developer.mozilla.org/docs/Glossary/Time_to_first_byte) (TTFB)
- [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP) - [First Contentful Paint](https://developer.mozilla.org/docs/Glossary/First_contentful_paint) (FCP)
- [Largest Contentful Paint](https://web.dev/lcp/) (LCP) - [Largest Contentful Paint](https://web.dev/lcp/) (LCP)
- [First Input Delay](https://web.dev/fid/) (FID)
- [Cumulative Layout Shift](https://web.dev/cls/) (CLS) - [Cumulative Layout Shift](https://web.dev/cls/) (CLS)
- [Interaction to Next Paint](https://web.dev/inp/) (INP) - [Interaction to Next Paint](https://web.dev/inp/) (INP)
......
...@@ -338,7 +338,6 @@ ...@@ -338,7 +338,6 @@
"stacktrace-parser@0.1.10": "patches/stacktrace-parser@0.1.10.patch", "stacktrace-parser@0.1.10": "patches/stacktrace-parser@0.1.10.patch",
"taskr@1.1.0": "patches/taskr@1.1.0.patch", "taskr@1.1.0": "patches/taskr@1.1.0.patch",
"minizlib@3.1.0": "patches/minizlib@3.1.0.patch", "minizlib@3.1.0": "patches/minizlib@3.1.0.patch",
"web-vitals@4.2.1": "patches/web-vitals@4.2.1.patch",
"@rspack/core@1.6.7": "patches/@rspack__core@1.6.7.patch", "@rspack/core@1.6.7": "patches/@rspack__core@1.6.7.patch",
"@modelcontextprotocol/sdk": "patches/@modelcontextprotocol__sdk.patch", "@modelcontextprotocol/sdk": "patches/@modelcontextprotocol__sdk.patch",
"@vercel/blob": "patches/@vercel__blob.patch", "@vercel/blob": "patches/@vercel__blob.patch",
......
...@@ -349,7 +349,7 @@ ...@@ -349,7 +349,7 @@
"util": "0.12.4", "util": "0.12.4",
"vm-browserify": "1.1.2", "vm-browserify": "1.1.2",
"watchpack": "2.4.0", "watchpack": "2.4.0",
"web-vitals": "4.2.1", "web-vitals": "6.2.1",
"webpack": "5.98.0", "webpack": "5.98.0",
"webpack-sources1": "npm:webpack-sources@1.4.3", "webpack-sources1": "npm:webpack-sources@1.4.3",
"webpack-sources3": "npm:webpack-sources@3.2.3", "webpack-sources3": "npm:webpack-sources@3.2.3",
......
import { useEffect } from 'react' import { useEffect } from 'react'
import { import {
onLCP, onLCP,
onFID,
onCLS, onCLS,
onINP, onINP,
onFCP, onFCP,
...@@ -13,11 +12,10 @@ export function useReportWebVitals( ...@@ -13,11 +12,10 @@ export function useReportWebVitals(
reportWebVitalsFn: (metric: Metric) => void reportWebVitalsFn: (metric: Metric) => void
) { ) {
useEffect(() => { useEffect(() => {
onCLS(reportWebVitalsFn) onCLS(reportWebVitalsFn, { reportSoftNavs: true })
onFID(reportWebVitalsFn) onLCP(reportWebVitalsFn, { reportSoftNavs: true })
onLCP(reportWebVitalsFn) onINP(reportWebVitalsFn, { reportSoftNavs: true })
onINP(reportWebVitalsFn) onFCP(reportWebVitalsFn, { reportSoftNavs: true })
onFCP(reportWebVitalsFn)
onTTFB(reportWebVitalsFn) onTTFB(reportWebVitalsFn)
}, [reportWebVitalsFn]) }, [reportWebVitalsFn])
} }
...@@ -346,7 +346,6 @@ export const experimentalSchema = { ...@@ -346,7 +346,6 @@ export const experimentalSchema = {
z.union([ z.union([
z.literal('CLS'), z.literal('CLS'),
z.literal('FCP'), z.literal('FCP'),
z.literal('FID'),
z.literal('INP'), z.literal('INP'),
z.literal('LCP'), z.literal('LCP'),
z.literal('TTFB'), z.literal('TTFB'),
......
...@@ -42,7 +42,7 @@ export type AppTreeType = ComponentType< ...@@ -42,7 +42,7 @@ export type AppTreeType = ComponentType<
* Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team. * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.
* https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting
*/ */
export const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'] as const export const WEB_VITALS = ['CLS', 'FCP', 'INP', 'LCP', 'TTFB'] as const
export type NextWebVitalsMetric = { export type NextWebVitalsMetric = {
id: string id: string
startTime: number startTime: number
......
diff --git a/dist/modules/types.d.ts b/dist/modules/types.d.ts
index 080d3667303398f9ee8cf782c43f2230ea72ef53..cdfe14ad4bdbe07023301dae36e7ea64a5048bf4 100644
--- a/dist/modules/types.d.ts
+++ b/dist/modules/types.d.ts
@@ -27,7 +27,8 @@ declare global {
}
interface PerformanceEventTiming extends PerformanceEntry {
duration: DOMHighResTimeStamp;
- interactionId: number;
+ // Waiting for https://github.com/GoogleChrome/web-vitals/commit/a92f8a78bce9e400366bc29db5fc23fdf23db469
+ readonly interactionId: number;
}
interface LayoutShiftAttribution {
node?: Node;
...@@ -53,9 +53,6 @@ patchedDependencies: ...@@ -53,9 +53,6 @@ patchedDependencies:
taskr@1.1.0: taskr@1.1.0:
hash: 1d0f571943b5d4761d4f2f39723796e402dd317f14a7c714e2021d3f12cc481c hash: 1d0f571943b5d4761d4f2f39723796e402dd317f14a7c714e2021d3f12cc481c
path: patches/taskr@1.1.0.patch path: patches/taskr@1.1.0.patch
web-vitals@4.2.1:
hash: f4d0a6719cc28520df7c47a0e2c2641759c2a0ad06ad57868c4c9d0567d4276d
path: patches/web-vitals@4.2.1.patch
webpack-sources@3.2.3: webpack-sources@3.2.3:
hash: 26afc15966a3fc37a3d1d366312a95ce66723513f6a3a720e4166a37147da8bd hash: 26afc15966a3fc37a3d1d366312a95ce66723513f6a3a720e4166a37147da8bd
path: patches/webpack-sources@3.2.3.patch path: patches/webpack-sources@3.2.3.patch
...@@ -1786,8 +1783,8 @@ importers: ...@@ -1786,8 +1783,8 @@ importers:
specifier: 2.4.0 specifier: 2.4.0
version: 2.4.0 version: 2.4.0
web-vitals: web-vitals:
specifier: 4.2.1 specifier: 6.2.1
version: 4.2.1(patch_hash=f4d0a6719cc28520df7c47a0e2c2641759c2a0ad06ad57868c4c9d0567d4276d) version: 6.2.1
webpack: webpack:
specifier: 5.98.0 specifier: 5.98.0
version: 5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.23))(esbuild@0.25.9) version: 5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.23))(esbuild@0.25.9)
...@@ -18550,8 +18547,8 @@ packages: ...@@ -18550,8 +18547,8 @@ packages:
web-namespaces@1.1.4: web-namespaces@1.1.4:
resolution: {integrity: sha512-wYxSGajtmoP4WxfejAPIr4l0fVh+jeMXZb08wNc0tMg6xsfZXj3cECqIK0G7ZAqUq0PP8WlMDtaOGVBTAWztNw==} resolution: {integrity: sha512-wYxSGajtmoP4WxfejAPIr4l0fVh+jeMXZb08wNc0tMg6xsfZXj3cECqIK0G7ZAqUq0PP8WlMDtaOGVBTAWztNw==}
web-vitals@4.2.1: web-vitals@6.2.1:
resolution: {integrity: sha512-U6bAxeudnhDqcXNl50JC4hLlqox9DZnngxfISZm3DMZnonW35xtJOVUc091L+DOY+6hVZVpKXoiCP0RiT6339Q==} resolution: {integrity: sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==}
web-worker@1.3.0: web-worker@1.3.0:
resolution: {integrity: sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==} resolution: {integrity: sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==}
...@@ -38553,7 +38550,7 @@ snapshots: ...@@ -38553,7 +38550,7 @@ snapshots:
web-namespaces@1.1.4: {} web-namespaces@1.1.4: {}
web-vitals@4.2.1(patch_hash=f4d0a6719cc28520df7c47a0e2c2641759c2a0ad06ad57868c4c9d0567d4276d): {} web-vitals@6.2.1: {}
web-worker@1.3.0: {} web-worker@1.3.0: {}
'use client' 'use client'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import Reporter from './reporter'
export default function ClientNestedLayout({ children }) { export default function ClientNestedLayout({ children }) {
const [count, setCount] = useState(0) const [count, setCount] = useState(0)
useEffect(() => { useEffect(() => {
setCount(1) setCount(1)
}, []) }, [])
function handleClick() {
const start = performance.now()
while (performance.now() - start < 200) {
// Ensure this interaction exceeds web-vitals' INP duration threshold.
}
setCount(count + 1)
}
return ( return (
<> <>
<Reporter />
<h1>Client Nested. Count: {count}</h1> <h1>Client Nested. Count: {count}</h1>
<button id="btn" onClick={() => setCount(count + 1)}> <button id="btn" onClick={handleClick}>
{count} {count}
</button> </button>
{children} {children}
......
import Reporter from './reporter'
export default function component() { export default function component() {
return ( return <h1>Test</h1>
<>
<h1>Test</h1>
<Reporter />
</>
)
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
import type { Page } from 'playwright'
describe('useReportWebVitals hook', () => { describe('useReportWebVitals hook', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -15,30 +16,45 @@ describe('useReportWebVitals hook', () => { ...@@ -15,30 +16,45 @@ describe('useReportWebVitals hook', () => {
await next.start() await next.start()
}) })
function collectWebVitals(page: Page, events: Array<Record<string, string>>) {
return page.route('https://example.vercel.sh/vitals', async (route) => {
events.push(
Object.fromEntries(
new URLSearchParams(route.request().postData() ?? '')
)
)
await route.fulfill()
})
}
// Analytics events are only sent in production // Analytics events are only sent in production
it('should send web-vitals', async () => { it('should send web-vitals', async () => {
await next.fetch('/report-web-vitals') await next.fetch('/report-web-vitals')
let eventsCount = 0 const events: Array<Record<string, string>> = []
const browser = await next.browser('/report-web-vitals', { const browser = await next.browser('/report-web-vitals', {
beforePageLoad: (page) => { beforePageLoad: async (currentPage) => {
page.route('https://example.vercel.sh/vitals', (route) => { await collectWebVitals(currentPage, events)
eventsCount += 1
route.fulfill()
})
}, },
}) })
// Refresh will trigger CLS and LCP. When page loads FCP and TTFB will trigger: // Refresh will report another set of navigation metrics.
await browser.refresh() await browser.refresh()
// After interaction LCP and FID will trigger // Exercise the interaction reporting path.
await browser.elementById('btn').click() await browser.elementById('btn').click()
// Make sure all registered events in performance-relayer has fired // Make sure all registered events in performance-relayer has fired
await check(async () => { await retry(() => {
expect(eventsCount).toBeGreaterThanOrEqual(6) expect(events.length).toBeGreaterThanOrEqual(4)
return 'success' })
}, 'success') expect(events.map((event) => event.name)).not.toContain('FID')
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
navigationURL: expect.stringMatching(/\/report-web-vitals$/),
}),
])
)
}) })
}) })
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