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.
For more advanced analytics and monitoring needs, Next.js provides a instrumentation-client.js|ts file that runs before your application’s frontend code starts executing. This is ideal for setting up global analytics, error tracking, or performance monitoring tools.
To use it, create an instrumentation-client.js or instrumentation-client.ts file in your application’s root directory:
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:
Next.js-hydration: Length of time it takes for the page to start and finish hydrating (in ms)
Next.js-route-change-to-render: Length of time it takes for a page to start rendering 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 separately:
exportfunctionreportWebVitals(metric) {
switch (metric.name) {
case'Next.js-hydration':
// handle hydration results
break
case'Next.js-route-change-to-render':
// handle route-change to render results
break
case'Next.js-render':
// handle render results
break
default:
break
}
}
These metrics work in all browsers that support the User Timing API.
Good to know: If you use Google Analytics, using the
id value can allow you to construct metric distributions manually (to calculate percentiles,
etc.)
useReportWebVitals((metric)=> {
// Use `window.gtag` if you initialized Google Analytics as this example: