#How to use web vitals in next 13.2
1 messages · Page 1 of 1 (latest)
Hi @signal mist. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To use Web Vitals in Next.js 13.2 with the app directory, you can follow these steps:
-
Create a custom
appcomponent file in yourappdirectory. If you don't have anappdirectory yet, follow the instructions in the Next.js 13 Upgrade Guide (https://beta.nextjs.org/docs/upgrade-guide) to create one and opt into the newappdirectory feature. -
Export a
reportWebVitalsfunction from your customappcomponent. Here's an example:
// app/_app.ts
export function reportWebVitals(metric) {
switch (metric.name) {
case 'FCP':
// handle FCP results
break;
case 'LCP':
// handle LCP results
break;
case 'CLS':
// handle CLS results
break;
case 'FID':
// handle FID results
break;
case 'TTFB':
// handle TTFB results
break;
case 'INP':
// handle INP results (note: INP is still an experimental metric)
break;
default:
break;
}
}
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
Next.js uses Google's web-vitals library (https://github.com/GoogleChrome/web-vitals#web-vitals) to measure the Web Vitals metrics available in reportWebVitals.
For more information on using Web Vitals with Next.js, refer to the Vercel documentation (https://vercel.com/docs/frameworks/nextjs).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@signal mist kapa.ai is still learning and improving, please let us how it did by reacting below
How does this work without an app file but instead with pages in the app directory?
@sinful jungle How does this work without an app file but instead with pages in the app directory?
Let me check the knowledge base for you. One moment! :books:
If you're using the app directory feature in Next.js 13.2 and want to use Web Vitals without a custom app component file, you can create a custom _app file inside the pages directory and follow the same steps as mentioned earlier.
Here's an example:
// app/pages/_app.ts
export function reportWebVitals(metric) {
switch (metric.name) {
case 'FCP':
// handle FCP results
break;
case 'LCP':
// handle LCP results
break;
case 'CLS':
// handle CLS results
break;
case 'FID':
// handle FID results
break;
case 'TTFB':
// handle TTFB results
break;
case 'INP':
// handle INP results (note: INP is still an experimental metric)
break;
default:
break;
}
}
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
This will work the same way as having a custom app component file in the app directory. The reportWebVitals function will be used to handle Web Vitals metrics in your Next.js application.