Mastering Core Web Vitals: A Complete Performance Optimization Guide
Deep dive into Core Web Vitals optimization, achieving 95+ Lighthouse scores, and implementing performance best practices for production websites.
Achieving exceptional web performance is crucial for user experience, SEO rankings, and business success. This comprehensive guide covers Core Web Vitals optimization, Lighthouse scoring, and proven techniques to achieve 95+ performance scores.
Understanding Core Web Vitals
Core Web Vitals are three specific metrics that Google uses to measure user experience:
Largest Contentful Paint (LCP) **Target: < 2.5 seconds**
LCP measures loading performance. Optimize by: - Using Next.js Image component with proper sizing - Implementing resource hints (preconnect, prefetch, preload) - Optimizing server response times - Using CDN for static assets - Eliminating render-blocking resources
// Optimize LCP with priority images
<Image
src="/hero-image.jpg"
alt="Hero"
width={1200}
height={600}
priority // Loads immediately
placeholder="blur"
/>First Input Delay (FID) / Interaction to Next Paint (INP) **Target: < 100ms for FID, < 200ms for INP**
Measures interactivity. Optimize by: - Code splitting and lazy loading - Minimizing JavaScript execution time - Using Web Workers for heavy computations - Optimizing third-party scripts
// Lazy load heavy components
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <Skeleton />,
ssr: false,
});Cumulative Layout Shift (CLS) **Target: < 0.1**
Measures visual stability. Optimize by: - Setting explicit dimensions for images and videos - Reserving space for dynamic content - Avoiding inserting content above existing content - Using aspect-ratio CSS property
// Prevent CLS with aspect ratio
<div className="aspect-video w-full">
<Image src="/video-thumb.jpg" fill />
</div>Achieving 95+ Lighthouse Scores
Image Optimization
// Use Next.js Image with optimization
import Image from 'next/image';
<Image
src="/product.jpg"
alt="Product"
width={800}
height={600}
quality={85}
format="webp"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>Font Optimization
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
preload: true,
variable: '--font-inter',
});Code Splitting
// Route-based code splitting (automatic in Next.js)
// Component-based code splitting
import dynamic from 'next/dynamic';
const Chart = dynamic(() => import('./Chart'), {
ssr: false,
loading: () => <ChartSkeleton />,
});Bundle Analysis
# Install bundle analyzer
npm install @next/bundle-analyzer
# Analyze bundle
ANALYZE=true npm run buildAdvanced Optimization Techniques
Server Components for Performance
// Server Component - no JavaScript sent to client
async function ProductList() {
const products = await fetchProducts();
return (
<ul>
{products.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}Static Generation with ISR
export async function generateStaticParams() {
const products = await fetchProducts();
return products.map((product) => ({
id: product.id.toString(),
}));
}
export const revalidate = 3600; // Revalidate every hourCaching Strategies
// API route with caching
export async function GET(request: Request) {
const data = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 }, // Cache for 1 hour
});
return Response.json(await data.json());
}Performance Monitoring
Lighthouse CI
# .lighthouserc.js
module.exports = {
ci: {
collect: {
numberOfRuns: 3,
url: ['http://localhost:3000'],
},
assert: {
assertions: {
'categories:performance': ['error', { minScore: 0.95 }],
'categories:accessibility': ['error', { minScore: 0.9 }],
'categories:best-practices': ['error', { minScore: 0.9 }],
'categories:seo': ['error', { minScore: 0.9 }],
},
},
},
};Real User Monitoring
// Track Core Web Vitals
export function reportWebVitals(metric: any) {
// Send to analytics
if (metric.label === 'web-vital') {
// Google Analytics
gtag('event', metric.name, {
value: Math.round(metric.value),
event_label: metric.id,
non_interaction: true,
});
// PostHog
posthog.capture('web_vital', {
name: metric.name,
value: metric.value,
});
}
}Best Practices Checklist
- [ ] All images optimized and using Next.js Image
- [ ] Fonts optimized with next/font
- [ ] JavaScript bundle size minimized
- [ ] Code splitting implemented
- [ ] Static generation where possible
- [ ] Caching headers configured
- [ ] Third-party scripts optimized
- [ ] LCP < 2.5s
- [ ] FID/INP < 100ms/200ms
- [ ] CLS < 0.1
- [ ] Lighthouse score 95+
Master these techniques to build lightning-fast, high-performing web applications that users love.