How to Use Web Vitals in Next.js for Performance Monitoring
In Next.js, you can use the built-in
reportWebVitals function exported from pages/_app.js to capture web vitals metrics like CLS, FID, and LCP. This function receives metric data which you can log or send to analytics services for performance monitoring.Syntax
The reportWebVitals function is exported from the pages/_app.js file in your Next.js app. It receives a metric object containing details about a web vital metric.
- metric.name: The name of the metric (e.g., CLS, FID, LCP).
- metric.value: The numeric value of the metric.
- metric.id: A unique ID for the metric event.
- metric.label: The category of the metric (e.g., 'web-vital').
You can use this function to log metrics or send them to an analytics endpoint.
javascript
export function reportWebVitals(metric) { console.log(metric) // You can send metric data to an analytics endpoint here }
Output
Logs metric objects like {name: 'CLS', value: 0.02, id: 'v1-...', label: 'web-vital'} to the console
Example
This example shows how to implement reportWebVitals in pages/_app.js to log web vitals metrics to the browser console.
javascript
import '../styles/globals.css' export function reportWebVitals(metric) { console.log('Web Vital Metric:', metric) } function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } export default MyApp
Output
When you load pages, the console logs objects like:
Web Vital Metric: {name: 'FCP', value: 1234.56, id: 'v1-...', label: 'web-vital'}
Common Pitfalls
- Not exporting
reportWebVitalsfrompages/_app.jsmeans Next.js won't report metrics. - Sending metrics asynchronously without error handling can lose data.
- Logging metrics only in development misses real user data; send metrics to a backend or analytics service.
- Confusing metric names or values can lead to wrong interpretations; always check official web vitals docs.
javascript
/* Wrong: Not exporting reportWebVitals */ function reportWebVitals(metric) { console.log(metric) } /* Right: Export the function */ export function reportWebVitals(metric) { console.log(metric) }
Quick Reference
Use this cheat sheet to remember key points about reportWebVitals in Next.js:
| Concept | Description |
|---|---|
| Function Location | Export from pages/_app.js |
| Parameter | Receives a metric object with name, value, id, label |
| Common Metrics | CLS, FID, LCP, FCP, TTFB |
| Usage | Log metrics or send to analytics backend |
| Important | Export function to enable reporting |
Key Takeaways
Export a reportWebVitals function from pages/_app.js to capture web vitals in Next.js.
The function receives metric objects with details like name and value for each web vital.
Use the function to log metrics or send them to analytics for real user monitoring.
Always export the function; otherwise, Next.js won't report web vitals.
Handle metrics carefully to avoid losing data and to get accurate performance insights.