Blog>
Snippets

Web Vitals Reporting in Next.js

Implement a function to monitor and report Web Vitals scores with Next.js to understand real-user performance on the web.
import { reportWebVitals } from 'next/vitals';

// Report Web Vitals to an analytics endpoint
export function reportWebVitals(metric) {
  const url = '/api/reportWebVitals'; // Define the endpoint URL

  // Construct the payload with metric data
  const body = JSON.stringify({
    name: metric.name,
    value: metric.value.toString(),
    id: metric.id,
  });

  // Use 'navigator.sendBeacon' if available, for sending data on page unload
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body);
  } else {
    fetch(url, {
      body,
      method: 'POST',
      keepalive: true,
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
}

// You have to include this snippet in your Next.js pages or '_app.js' to set up the report handler
// This is an example that logs the metrics to the console
import { reportWebVitals } from '../path-to-your-reporting-function';

export function MyApp({ Component, pageProps }) {
  // Pass Web Vitals reporting function during runtime
  reportWebVitals(console.log);

  // Render your application
  return <Component {...pageProps} />;
}
This code snippet provides a function to report Web Vitals metrics for a Next.js application. Firstly, it defines the `reportWebVitals` function, which is then exported. Inside the function, the metric data is structured into a payload and sent to a specified API endpoint. `navigator.sendBeacon` is used when available as it allows the data to be transmitted asynchronously when the page session ends. For older browsers, a `fetch` request with the `keepalive` flag is used instead. Additionally, an example to integrate the reporting function in a Next.js application is shown, including it in `_app.js` and passing it to report the metrics.