How do you optimize Core Web Vitals in Next.js?
Answer
Next.js is designed for excellent Core Web Vitals but requires correct implementation: LCP (Largest Contentful Paint — target: <2.5s): (1) Add priority prop to the LCP image — disables lazy loading, adds preload hint; (2) Serve images via CDN with next/image; (3) Use SSR/SSG for fast initial HTML; (4) Streaming SSR — send HTML immediately; (5) Preconnect to important third-party origins. FID/INP (Interaction to Next Paint — target: <200ms): (1) Minimize JavaScript with Server Components; (2) Code split with dynamic imports; (3) Avoid long tasks blocking main thread; (4) Use web workers for CPU-heavy client work; (5) Optimize third-party scripts with afterInteractive/lazyOnload. CLS (Cumulative Layout Shift — target: <0.1): (1) Always specify width/height on images (next/image enforces this); (2) Reserve space for embeds, ads, dynamic content; (3) Avoid inserting content above existing content; (4) Use CSS aspect-ratio for responsive media; (5) Don't use animations that move layout (prefer opacity, transform). TTFB (Time to First Byte — target: <800ms): (1) Use static generation where possible; (2) ISR for frequently-updated content; (3) Edge caching (Vercel Edge Network); (4) Server-close-to-user deployment; (5) Efficient database queries in SSR. Measuring: Next.js Analytics (Vercel), Chrome DevTools Performance tab, Lighthouse, web-vitals library: import { onCLS, onINP, onLCP } from "web-vitals";.