Image Optimization
Overview
The next/image component extends the standard <img> tag to provide automatic size optimization, lazy loading, layout shift prevention, and modern formats like WebP/AVIF. It drastically improves Core Web Vitals.
Syntax
import Image from 'next/image';
import localPic from '@/public/hero.jpg';
export default function Page() {
return (
<div>
{/* Local image: width/height automatically inferred */}
<Image src={localPic} alt="Hero" priority />
{/* Remote image: must provide width and height */}
<Image
src="https://external.com/photo.jpg"
alt="Remote"
width={500}
height={300}
/>
</div>
);
}Common Pitfalls
Forgetting to whitelist external domains in
next.config.js. Remote images will fail to load for security reasons otherwise.Not adding the
priorityprop to images above the fold (like hero images), causing slow LCP (Largest Contentful Paint).
Interview Questions
How does next/image prevent Cumulative Layout Shift (CLS)?
It requires width and height attributes (or infers them for local images) to reserve the exact space in the DOM before the image loads, preventing content from jumping around.
Real-World Example
Configuring remote image patterns in next.config.js.
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
],
},
};Check Your Knowledge
Test your understanding of Image Optimization with these quick questions.