Learn the concept
Performance Optimization
Next.js provides automatic optimizations including code splitting per route, image optimization via next/image, font optimization with next/font, script loading control with next/script, Server Components to reduce JavaScript bundles, Suspense for streaming, automatic prefetching of links, and edge deployment capabilities.
next/dynamic for component-level splittingoptimizePackageImports for tree-shakingsizes attributebeforeInteractive, afterInteractive, lazyOnloadworker strategyprefetch propnpm install @next/bundle-analyzerdynamic: Force static or dynamicrevalidate: Cache durationfetchCache: Control fetch cachingimport Image from 'next/image';
// Hero image - prioritize loading
export function Hero() {
return (
<Image
src="/hero.jpg"
alt="Hero image"
width={1920}
height={1080}
preload // Load immediately, no lazy loading (replaces priority)
placeholder="blur"
blurDataURL="data:image/jpeg;base64,..." // Low-res placeholder
/>
);
}
// Responsive image with sizes
export function ProductImage({ src, alt }: { src: string; alt: string }) {
return (
<Image
src={src}
alt={alt}
fill // Fills parent container
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
className="object-cover"
/>
);
}
// next.config.js - Remote image domains
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'cdn.example.com',
pathname: '/images/**',
},
],
formats: ['image/avif', 'image/webp'],
},
};Using next/image with preload for LCP, next/font for CLS prevention, and code splitting for INP improvement
Using next/script with afterInteractive and lazyOnload strategies to prevent third-party scripts from blocking page load
Using Suspense boundaries and streaming to show content incrementally, improving perceived performance
Take a poorly performing Next.js page and optimize with next/image, next/font, dynamic imports, and Suspense, measuring with Lighthouse
Set up @next/bundle-analyzer, identify large dependencies, and optimize with dynamic imports and tree-shaking