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