Unverified Commit ffb3ce24 authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Report Web Vitals for soft navigations

Upgrades the vendored `web-vitals` to v6 and passes `reportSoftNavs: true`
to `onCLS`, `onINP` and `onLCP` in `useReportWebVitals`, so that the Core
Web Vitals are also measured for soft navigations (client-side navigations
that change the URL) in browsers that support the Soft Navigations API,
which shipped in Chrome 151. Metrics measured for a soft navigation are
reported with a `navigationType` of `soft-navigation` and the
`navigationURL` they belong to.

FCP and TTFB keep reporting for the initial page load only, since a soft
navigation has no server request and `web-vitals` would report a TTFB of 0.

`web-vitals` v5 removed `onFID`, so FID is no longer reported and is
removed from `WEB_VITALS`, the `experimental.webVitalsAttribution` schema
and the docs. The v4 patch that made `PerformanceEventTiming.interactionId`
readonly is no longer needed, as that landed upstream.

<!-- NEXT_JS_LLM -->
Co-Authored-By: 's avatarClaude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: 's avatarMalte Ubl <89679+cramforce@users.noreply.github.com>
parent 3c97df56
......@@ -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)
- [First Contentful Paint](https://developer.mozilla.org/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)
- [Interaction to Next Paint](https://web.dev/inp/) (INP)
......
......@@ -69,10 +69,11 @@ export default function Layout({ children }) {
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
- `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, CLS, INP) 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.
- `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"` (see [Soft navigations](#soft-navigations)).
- `navigationURL`: The URL the metric was measured for. Metrics are often reported after the fact, so use this instead of the current URL when attributing a metric to a page.
- `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.
......@@ -84,12 +85,33 @@ 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)
- [First Contentful Paint](https://developer.mozilla.org/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)
- [Interaction to Next Paint](https://web.dev/inp/) (INP)
You can handle all the results of these metrics using the `name` property.
## Soft navigations
The Core Web Vitals (LCP, CLS, and INP) are also measured for soft navigations, i.e. client-side
navigations that update the URL without a full page load. This requires browser support for the
[Soft Navigations API](https://developer.chrome.com/docs/web-platform/soft-navigations) (Chrome 151
and newer). In browsers without support, the Core Web Vitals are measured for the initial page load
only.
Metrics that were measured for a soft navigation have a `navigationType` of `"soft-navigation"`.
Since a metric can be reported after another navigation already happened, use `navigationURL` to
attribute a metric to the page it was measured for:
```js
const logWebVitals = (metric) => {
console.log(metric.navigationURL, metric.name, metric.value)
}
```
> **Good to know**: Enabling soft navigation measurement also changes how the initial page load is
> measured, because its metrics are finalized as soon as the first soft navigation happens, instead
> of when the page is unloaded.
<PagesOnly>
```jsx filename="pages/_app.js"
......
......@@ -340,7 +340,6 @@
"stacktrace-parser@0.1.10": "patches/stacktrace-parser@0.1.10.patch",
"taskr@1.1.0": "patches/taskr@1.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",
"@modelcontextprotocol/sdk": "patches/@modelcontextprotocol__sdk.patch",
"@vercel/blob": "patches/@vercel__blob.patch",
......
......@@ -349,7 +349,7 @@
"util": "0.12.4",
"vm-browserify": "1.1.2",
"watchpack": "2.4.0",
"web-vitals": "4.2.1",
"web-vitals": "6.1.0",
"webpack": "5.98.0",
"webpack-sources1": "npm:webpack-sources@1.4.3",
"webpack-sources3": "npm:webpack-sources@3.2.3",
......
/**
* @jest-environment jsdom
*/
/* eslint-disable @next/internal/typechecked-require -- Not a prod file */
/* eslint-disable import/no-extraneous-dependencies -- Not a prod file */
import type * as WebVitals from './web-vitals'
jest.mock('next/dist/compiled/web-vitals', () => ({
onCLS: jest.fn(),
onFCP: jest.fn(),
onINP: jest.fn(),
onLCP: jest.fn(),
onTTFB: jest.fn(),
}))
type WebVitalsMocks = Record<
'onCLS' | 'onFCP' | 'onINP' | 'onLCP' | 'onTTFB',
jest.Mock
>
describe('useReportWebVitals', () => {
let cleanup: typeof import('@testing-library/react').cleanup
let renderHook: typeof import('@testing-library/react').renderHook
let useReportWebVitals: typeof WebVitals.useReportWebVitals
let webVitals: WebVitalsMocks
beforeEach(() => {
jest.resetModules()
useReportWebVitals = (require('./web-vitals') as typeof WebVitals)
.useReportWebVitals
webVitals = require('next/dist/compiled/web-vitals') as WebVitalsMocks
const rtl = require('@testing-library/react/pure')
renderHook = rtl.renderHook
cleanup = rtl.cleanup
})
afterEach(() => {
cleanup()
})
it('reports the Core Web Vitals for soft navigations', () => {
const report = jest.fn()
renderHook(() => useReportWebVitals(report))
for (const onCoreWebVital of [
webVitals.onCLS,
webVitals.onINP,
webVitals.onLCP,
]) {
expect(onCoreWebVital).toHaveBeenCalledTimes(1)
expect(onCoreWebVital).toHaveBeenCalledWith(report, {
reportSoftNavs: true,
})
}
})
it('reports FCP and TTFB for the initial page load only', () => {
const report = jest.fn()
renderHook(() => useReportWebVitals(report))
for (const onLoadMetric of [webVitals.onFCP, webVitals.onTTFB]) {
expect(onLoadMetric).toHaveBeenCalledTimes(1)
expect(onLoadMetric).toHaveBeenCalledWith(report)
}
})
it('does not register the same callback twice on re-render', () => {
const report = jest.fn()
const { rerender } = renderHook(() => useReportWebVitals(report))
rerender()
expect(webVitals.onLCP).toHaveBeenCalledTimes(1)
})
})
import { useEffect } from 'react'
import {
onLCP,
onFID,
onCLS,
onINP,
onFCP,
......@@ -9,14 +8,25 @@ import {
} from 'next/dist/compiled/web-vitals'
import type { Metric } from 'next/dist/compiled/web-vitals'
// Report the Core Web Vitals for soft navigations (client-side navigations) in
// addition to the initial page load. `web-vitals` feature detects the Soft
// Navigations API and keeps reporting only for the initial page load in
// browsers that don't support it.
// Metrics reported for a soft navigation have a `navigationType` of
// `'soft-navigation'` and a `navigationURL` of the URL they were measured for.
// https://github.com/GoogleChrome/web-vitals#report-metrics-for-soft-navigations
const softNavsOpts = { reportSoftNavs: true }
export function useReportWebVitals(
reportWebVitalsFn: (metric: Metric) => void
) {
useEffect(() => {
onCLS(reportWebVitalsFn)
onFID(reportWebVitalsFn)
onLCP(reportWebVitalsFn)
onINP(reportWebVitalsFn)
onCLS(reportWebVitalsFn, softNavsOpts)
onLCP(reportWebVitalsFn, softNavsOpts)
onINP(reportWebVitalsFn, softNavsOpts)
// FCP and TTFB are load metrics, so they keep reporting for the initial
// page load only. Reporting TTFB for soft navigations would only ever
// report `0`, since no server request is involved.
onFCP(reportWebVitalsFn)
onTTFB(reportWebVitalsFn)
}, [reportWebVitalsFn])
......
......@@ -342,7 +342,6 @@ export const experimentalSchema = {
z.union([
z.literal('CLS'),
z.literal('FCP'),
z.literal('FID'),
z.literal('INP'),
z.literal('LCP'),
z.literal('TTFB'),
......
......@@ -42,7 +42,7 @@ export type AppTreeType = ComponentType<
* 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
*/
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 = {
id: string
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:
taskr@1.1.0:
hash: 1d0f571943b5d4761d4f2f39723796e402dd317f14a7c714e2021d3f12cc481c
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:
hash: 26afc15966a3fc37a3d1d366312a95ce66723513f6a3a720e4166a37147da8bd
path: patches/webpack-sources@3.2.3.patch
......@@ -1783,8 +1780,8 @@ importers:
specifier: 2.4.0
version: 2.4.0
web-vitals:
specifier: 4.2.1
version: 4.2.1(patch_hash=f4d0a6719cc28520df7c47a0e2c2641759c2a0ad06ad57868c4c9d0567d4276d)
specifier: 6.1.0
version: 6.1.0
webpack:
specifier: 5.98.0
version: 5.98.0(@swc/core@1.11.24(@swc/helpers@0.5.23))(esbuild@0.25.9)
......@@ -17936,8 +17933,8 @@ packages:
web-namespaces@1.1.4:
resolution: {integrity: sha512-wYxSGajtmoP4WxfejAPIr4l0fVh+jeMXZb08wNc0tMg6xsfZXj3cECqIK0G7ZAqUq0PP8WlMDtaOGVBTAWztNw==}
web-vitals@4.2.1:
resolution: {integrity: sha512-U6bAxeudnhDqcXNl50JC4hLlqox9DZnngxfISZm3DMZnonW35xtJOVUc091L+DOY+6hVZVpKXoiCP0RiT6339Q==}
web-vitals@6.1.0:
resolution: {integrity: sha512-ZNoJ/MbU6aaR2WjKrFVUvy5WQx+G96YvXQFSsmKTz3A/0VlAFywjUcxl00hc/S6wef2stfgQ4yWYIJCWCNudkA==}
web-worker@1.3.0:
resolution: {integrity: sha512-BSR9wyRsy/KOValMgd5kMyr3JzpdeoR9KVId8u5GVlTTAtNChlsE4yTxeY7zMdNSyOmoKBv8NH2qeRY9Tg+IaA==}
......@@ -37424,7 +37421,7 @@ snapshots:
web-namespaces@1.1.4: {}
web-vitals@4.2.1(patch_hash=f4d0a6719cc28520df7c47a0e2c2641759c2a0ad06ad57868c4c9d0567d4276d): {}
web-vitals@6.1.0: {}
web-worker@1.3.0: {}
export default function component() {
return (
<>
<h1 id="destination">Destination</h1>
{/* Some content to paint, so that the client-side navigation to this page
can be detected as a soft navigation by the browser. */}
<p>{'Lorem ipsum dolor sit amet. '.repeat(100)}</p>
</>
)
}
'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import Reporter from './reporter'
export default function ClientNestedLayout({ children }) {
const [count, setCount] = useState(0)
......@@ -13,6 +15,12 @@ export default function ClientNestedLayout({ children }) {
<button id="btn" onClick={() => setCount(count + 1)}>
{count}
</button>
<Link href="/report-web-vitals/destination" id="to-destination">
To destination
</Link>
{/* Rendered by the layout, so that it stays mounted across client-side
navigations, like a root layout would. */}
<Reporter />
{children}
</>
)
......
import Reporter from './reporter'
export default function component() {
return (
<>
<h1>Test</h1>
<Reporter />
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { retry } from 'next-test-utils'
type ReportedMetric = Record<string, string>
describe('useReportWebVitals hook', () => {
const { next } = nextTestSetup({
......@@ -15,30 +17,102 @@ describe('useReportWebVitals hook', () => {
await next.start()
})
// Analytics events are only sent in production
it('should send web-vitals', async () => {
await next.fetch('/report-web-vitals')
// The reporter posts every metric to `https://example.vercel.sh/vitals`, which
// is intercepted here so that the reported metrics can be asserted on.
async function openReportWebVitalsPage() {
const metrics: ReportedMetric[] = []
let eventsCount = 0
const browser = await next.browser('/report-web-vitals', {
beforePageLoad: (page) => {
page.route('https://example.vercel.sh/vitals', (route) => {
eventsCount += 1
metrics.push(
Object.fromEntries(
new URLSearchParams(route.request().postData() ?? '')
)
)
route.fulfill()
})
},
})
// Refresh will trigger CLS and LCP. When page loads FCP and TTFB will trigger:
await browser.refresh()
return { browser, metrics }
}
// After interaction LCP and FID will trigger
// Analytics events are only sent in production
it('should send web-vitals', async () => {
await next.fetch('/report-web-vitals')
const { browser, metrics } = await openReportWebVitalsPage()
// Interacting with the page is required for INP to be measured.
await browser.elementById('btn').click()
// Make sure all registered events in performance-relayer has fired
await check(async () => {
expect(eventsCount).toBeGreaterThanOrEqual(6)
return 'success'
}, 'success')
// Refreshing hides the current page, which finalizes CLS, INP and LCP for
// it. Loading the page again reports FCP and TTFB another time.
await browser.refresh()
await retry(async () => {
expect(metrics.map((metric) => metric.name)).toEqual(
expect.arrayContaining(['CLS', 'FCP', 'INP', 'LCP', 'TTFB'])
)
})
// Metrics are reported for the URL they were measured for, which is not
// necessarily the URL of the page at the time of reporting.
for (const metric of metrics) {
expect(metric.navigationURL).toContain('/report-web-vitals')
}
})
it('should send web-vitals for soft navigations', async () => {
await next.fetch('/report-web-vitals/destination')
const { browser, metrics } = await openReportWebVitalsPage()
// Soft navigations are only measured by browsers that support the Soft
// Navigations API (Chromium 151+). `web-vitals` feature detects it, and
// keeps reporting metrics for the initial page load only otherwise.
const supportsSoftNavigations = await browser.eval(
() =>
PerformanceObserver.supportedEntryTypes.includes('soft-navigation') &&
typeof (globalThis as any).PerformanceSoftNavigation?.prototype
?.getLargestInteractionContentfulPaint === 'function'
)
await browser.elementById('to-destination').click()
await retry(async () => {
expect(await browser.elementById('destination').text()).toBe(
'Destination'
)
})
// Hiding the page finalizes the metrics that are still pending for it.
await browser.refresh()
await retry(async () => {
expect(metrics.map((metric) => metric.name)).toEqual(
expect.arrayContaining(['CLS', 'FCP', 'LCP', 'TTFB'])
)
})
const softNavigationMetrics = metrics.filter(
(metric) => metric.navigationType === 'soft-navigation'
)
if (!supportsSoftNavigations) {
expect(softNavigationMetrics).toEqual([])
return
}
// The Core Web Vitals are measured again for the soft navigation, and are
// reported for the URL that was navigated to.
expect(softNavigationMetrics.map((metric) => metric.name)).toEqual(
expect.arrayContaining(['LCP'])
)
for (const metric of softNavigationMetrics) {
expect(metric.navigationURL).toContain('/report-web-vitals/destination')
}
})
})
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