How toReport Web Vitals in Next.js

To get a report on Web Vitals while using Next.js create a pages/_app.js, if you don't already have one, and add the following line:

export function reportWebVitals(metric) {
  console.log(metric);
}

Next.js will automatically start to keep track of multiple metrics and give you back a report per metric, you can see it running in pokedex-swr.now.sh. The metrics we can track include:

Next.js-hydration is the amount of time it takes a page to start and finish hydrating the HTML.

Next.js-route-change-to-render is the amount of time it takes a page to start rendering after a route change.

Next.js-render is the amount of time it takes a page to finish rendering after a route change.

If you want to learn more about the first five follow the links above.

Once you have the report you can start tracking them however your prefer, if you are using Google Analytics you could replace the console.log with:

export function reportWebVitals({ id, name, label, value }) {
  ga("send", "event", {
    eventCategory: `Next.js ${label} metric`,
    eventAction: name,
    eventValue: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers
    eventLabel: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate.
  });
}

Now we will start sending those metric to Google Analytics and keep track of them, we could then use them to detect slow pages and fix them.