How to add analytics to your Next.js application
Measure and track page performance using Next.js Speed Insights
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.
Client Instrumentation
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:
Build Your Own
Since the useReportWebVitals hook must be used in a Client Component, create a separate file for the WebVitals component with 'use client' at the top, before any imports. Import this component into the root layout to keep the client boundary limited to this module and its imports.
View the API Reference for more information.
Web Vitals
Web Vitals are a set of useful metrics that aim to capture the user experience of a web page. The following web vitals are all included:
- Time to First Byte (TTFB)
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- Cumulative Layout Shift (CLS)
- Interaction to Next Paint (INP)
You can handle all the results of these metrics using the name property.
Sending results to external systems
You can send results to any endpoint to measure and track real user performance on your site. For example:
Good to know: If you use Google Analytics, using the
id value can allow you to construct metric distributions manually (to calculate percentiles,
etc.)
Read more about sending results to Google Analytics.