๐ŸŽ‰ berenickt ๋ธ”๋กœ๊ทธ์— ์˜จ ๊ฑธ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค. ๐ŸŽ‰
Front
NextJs
Analytics

Analytics

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 to automatically collect and visualize metrics for you.


Build Your Own

app/_components/web-vitals.js
1
'use client'
2
3
import { useReportWebVitals } from 'next/web-vitals'
4
5
export function WebVitals() {
6
useReportWebVitals(metric => {
7
console.log(metric)
8
})
9
}
app/layout.js
1
import { WebVitals } from './_components/web-vitals'
2
3
export default function Layout({ children }) {
4
return (
5
<html>
6
<body>
7
<WebVitals />
8
{children}
9
</body>
10
</html>
11
)
12
}

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 for more information.


Web Vitals

Web 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:

You can handle all the results of these metrics using the name property.

app/components/web-vitals.tsx
1
'use client'
2
3
import { useReportWebVitals } from 'next/web-vitals'
4
5
export function WebVitals() {
6
useReportWebVitals(metric => {
7
switch (metric.name) {
8
case 'FCP': {
9
// handle FCP results
10
}
11
case 'LCP': {
12
// handle LCP results
13
}
14
// ...
15
}
16
})
17
}

Sending results to external systems

You can send results to any endpoint to measure and track real user performance on your site. For example:

1
useReportWebVitals(metric => {
2
const body = JSON.stringify(metric)
3
const url = 'https://example.com/analytics'
4
5
// Use `navigator.sendBeacon()` if available, falling back to `fetch()`.
6
if (navigator.sendBeacon) {
7
navigator.sendBeacon(url, body)
8
} else {
9
fetch(url, { body, method: 'POST', keepalive: true })
10
}
11
})

Good to know: If you use Google Analytics, using the id value can allow you to construct metric distributions manually (to calculate percentiles, etc.)

1
useReportWebVitals(metric => {
2
// Use `window.gtag` if you initialized Google Analytics as this example:
3
// https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_app.js
4
window.gtag('event', metric.name, {
5
value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), // values must be integers
6
event_label: metric.id, // id unique to current page load
7
non_interaction: true, // avoids affecting bounce rate.
8
});
9
}

Read more about sending results to Google Analytics.