Optimizing Core Web Vitals in Next.js 15 App Router
Frontend Team
Web Engineering
Understanding Core Web Vitals
Google's Core Web Vitals are critical metrics that measure the real-world user experience of a web page. With the introduction of the Next.js App Router, the strategies for optimizing these metrics have evolved.
1. Optimizing LCP (Largest Contentful Paint)
LCP measures loading performance. To provide a good user experience, LCP should occur within 2.5 seconds of when the page first starts loading.
Strategies in Next.js:
- Use the
next/imagecomponent with thepriorityprop for hero images. - Preload critical fonts using
next/font. - Keep the critical rendering path clear by deferring non-essential CSS and JS.
- Utilize Server Components to render HTML on the server, avoiding client-side data fetching waterfalls.
2. Improving INP (Interaction to Next Paint)
INP assesses a page's overall responsiveness to user interactions.
Strategies in Next.js:
- Minimize main thread blocking by breaking up long tasks.
- Defer non-critical third-party scripts using
next/scriptwith thestrategy="lazyOnload"orstrategy="worker"(experimental). - Use React 18's
useTransitionfor non-urgent UI updates to keep the interface responsive during state changes.
3. Fixing CLS (Cumulative Layout Shift)
CLS measures visual stability. Unexpected layout shifts disrupt the user experience.
Strategies in Next.js:
- Always define
widthandheighton<img>tags, or usenext/imagewhich handles this automatically. - Avoid inserting content above existing content dynamically.
- Use CSS aspect-ratio boxes for ad slots or dynamic content areas before they load.
- Ensure custom fonts don't cause FOUT (Flash of Unstyled Text) by using
next/fontwhich utilizes CSSsize-adjust.
Conclusion
Performance is a continuous process. By leveraging the built-in optimizations of the Next.js App Router and keeping a close eye on your Core Web Vitals, you can build extremely fast web applications.
