Unverified Commit 0cdddd41 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

docs: update analytics docs for `useReportWebVitals` (#58196)

[This
page](https://nextjs.org/docs/app/building-your-application/optimizing/analytics)
was not yet mentioning `useReportWebVitals`.

Closes https://github.com/vercel/next.js/issues/57715.
parent 4024b25e
...@@ -5,48 +5,62 @@ description: Measure and track page performance using Next.js Speed Insights ...@@ -5,48 +5,62 @@ description: Measure and track page performance using Next.js Speed Insights
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */} {/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
[Next.js Speed Insights](https://nextjs.org/analytics) allows you to analyze and measure the performance of Next.js has built-in support for measuring and reporting performance metrics. You can either use the `useReportWebVitals` hook to manage reporting yourself, or alternatively, Vercel provides a [managed service](https://vercel.com/analytics?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) to automatically collect and visualize metrics for you.
pages using different metrics.
You can start collecting your [Real Experience Score](https://vercel.com/docs/concepts/speed-insights#core-web-vitals-explained?utm_source=next-site&utm_medium=docs&utm_campaign=next-website) with zero-configuration on [Vercel deployments](https://vercel.com/docs/concepts/speed-insights?utm_source=next-site&utm_medium=docs&utm_campaign=next-website).
The rest of this documentation describes the built-in relayer Next.js Speed Insights uses.
<PagesOnly>
## Build Your Own ## Build Your Own
First, you will need to create a [custom App](/docs/pages/building-your-application/routing/custom-app) component and define a `reportWebVitals` function: <PagesOnly>
```jsx filename="pages/_app.js" ```jsx filename="pages/_app.js"
export function reportWebVitals(metric) { import { useReportWebVitals } from 'next/web-vitals'
console.log(metric)
}
function MyApp({ Component, pageProps }) { function MyApp({ Component, pageProps }) {
useReportWebVitals((metric) => {
console.log(metric)
})
return <Component {...pageProps} /> return <Component {...pageProps} />
} }
export default MyApp
``` ```
This function is fired when the final values for any of the metrics have finished calculating on View the [API Reference](/docs/pages/api-reference/functions/use-report-web-vitals) for more information.
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: </PagesOnly>
- `id`: Unique identifier for the metric in the context of the current page load <AppOnly>
- `name`: Metric name
- `startTime`: First recorded timestamp of the performance entry in [milliseconds](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) (if applicable)
- `value`: Value, or duration in [milliseconds](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp), of the performance entry
- `label`: Type of metric (`web-vital` or `custom`)
There are two types of metrics that are tracked: ```jsx filename="app/_components/web-vitals.js"
'use client'
- Web Vitals import { useReportWebVitals } from 'next/web-vitals'
- Custom metrics
</PagesOnly> export function WebVitals() {
useReportWebVitals((metric) => {
console.log(metric)
})
}
```
```jsx filename="app/layout.js"
import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
return (
<html>
<body>
<WebVitals />
{children}
</body>
</html>
)
}
```
> Since the `useReportWebVitals` hook requires the `"use client"` directive, the most performant approach is to create a separate component that the root layout imports. This confines the client boundary exclusively to the `WebVitals` component.
View the [API Reference](/docs/app/api-reference/functions/use-report-web-vitals) for more information.
</AppOnly>
## Web Vitals ## Web Vitals
...@@ -58,55 +72,81 @@ experience of a web page. The following web vitals are all included: ...@@ -58,55 +72,81 @@ experience of a web page. The following web vitals are all included:
- [Largest Contentful Paint](https://web.dev/lcp/) (LCP) - [Largest Contentful Paint](https://web.dev/lcp/) (LCP)
- [First Input Delay](https://web.dev/fid/) (FID) - [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) _(experimental)_ - [Interaction to Next Paint](https://web.dev/inp/) (INP)
You can handle all the results of these metrics using the `name` property.
<PagesOnly> <PagesOnly>
You can handle all the results of these metrics using the `web-vital` label: ```jsx filename="pages/_app.js"
import { useReportWebVitals } from 'next/web-vitals'
```js function MyApp({ Component, pageProps }) {
export function reportWebVitals(metric) { useReportWebVitals((metric) => {
if (metric.label === 'web-vital') { switch (metric.name) {
console.log(metric) // The metric object ({ id, name, startTime, value, label }) is logged to the console case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results
}
// ...
} }
})
return <Component {...pageProps} />
} }
``` ```
There's also the option of handling each of the metrics separately: </PagesOnly>
<AppOnly>
```js ```tsx filename="app/components/web-vitals.tsx" switcher
export function reportWebVitals(metric) { 'use client'
import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) { switch (metric.name) {
case 'FCP': case 'FCP': {
// handle FCP results // handle FCP results
break }
case 'LCP': case 'LCP': {
// handle LCP results // handle LCP results
break
case 'CLS':
// handle CLS results
break
case 'FID':
// handle FID results
break
case 'TTFB':
// handle TTFB results
break
case 'INP':
// handle INP results (note: INP is still an experimental metric)
break
default:
break
} }
// ...
}
})
} }
``` ```
A third-party library, [web-vitals](https://github.com/GoogleChrome/web-vitals), is used to measure ```jsx filename="app/components/web-vitals.js" switcher
these metrics. Browser compatibility depends on the particular metric, so refer to the [Browser 'use client'
Support](https://github.com/GoogleChrome/web-vitals#browser-support) section to find out which
browsers are supported.
## Custom metrics import { useReportWebVitals } from 'next/web-vitals'
export function WebVitals() {
useReportWebVitals((metric) => {
switch (metric.name) {
case 'FCP': {
// handle FCP results
}
case 'LCP': {
// handle LCP results
}
// ...
}
})
}
```
</AppOnly>
<PagesOnly>
## Custom Metrics
In addition to the core metrics listed above, there are some additional custom metrics that 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: measure the time it takes for the page to hydrate and render:
...@@ -116,17 +156,7 @@ measure the time it takes for the page to hydrate and render: ...@@ -116,17 +156,7 @@ measure the time it takes for the page to hydrate and render:
route change (in ms) route change (in ms)
- `Next.js-render`: Length of time it takes for a page to finish render 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: You can handle all the results of these metrics separately:
```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 ```js
export function reportWebVitals(metric) { export function reportWebVitals(metric) {
...@@ -148,13 +178,15 @@ export function reportWebVitals(metric) { ...@@ -148,13 +178,15 @@ export function reportWebVitals(metric) {
These metrics work in all browsers that support the [User Timing API](https://caniuse.com/#feat=user-timing). These metrics work in all browsers that support the [User Timing API](https://caniuse.com/#feat=user-timing).
</PagesOnly>
## Sending results to external systems ## Sending results to external systems
With the relay function, you can send results to any endpoint to measure and track You can send results to any endpoint to measure and track
real user performance on your site. For example: real user performance on your site. For example:
```js ```js
export function reportWebVitals(metric) { useReportWebVitals((metric) => {
const body = JSON.stringify(metric) const body = JSON.stringify(metric)
const url = 'https://example.com/analytics' const url = 'https://example.com/analytics'
...@@ -164,57 +196,23 @@ export function reportWebVitals(metric) { ...@@ -164,57 +196,23 @@ export function reportWebVitals(metric) {
} else { } else {
fetch(url, { body, method: 'POST', keepalive: true }) fetch(url, { body, method: 'POST', keepalive: true })
} }
} })
``` ```
> **Good to know**: If you use [Google Analytics](https://analytics.google.com/analytics/web/), using the > **Good to know**: 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, > `id` value can allow you to construct metric distributions manually (to calculate percentiles,
> etc.) > etc.)
>
> ```js > ```js
> export function reportWebVitals({ id, name, label, value }) { > useReportWebVitals(metric => {
> // Use `window.gtag` if you initialized Google Analytics as this example: > // Use `window.gtag` if you initialized Google Analytics as this example:
> // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js > // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js
> window.gtag('event', name, { > window.gtag('event', metric.name, {
> event_category: > value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), // values must be integers
> label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric', > event_label: metric.id, // id unique to current page load
> value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
> event_label: id, // id unique to current page load
> non_interaction: true, // avoids affecting bounce rate. > non_interaction: true, // avoids affecting bounce rate.
> }) > });
> } > }
> ``` > ```
> >
> Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics). > Read more about [sending results to Google Analytics](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics).
## TypeScript
If you are using TypeScript, you can use the built-in type `NextWebVitalsMetric`:
```tsx filename="pages/_app.tsx" switcher
import type { AppProps, NextWebVitalsMetric } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export function reportWebVitals(metric: NextWebVitalsMetric) {
console.log(metric)
}
export default MyApp
```
```jsx filename="pages/_app.js" switcher
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export function reportWebVitals(metric) {
console.log(metric)
}
export default MyApp
```
</PagesOnly>
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