Topic 37 of 47
Image Component Optimization
Overview
The Next.js `<Image>` component extends the HTML `<img>` element. It automatically optimizes images by converting them to modern formats (WebP/AVIF), preventing Layout Shifts, and lazy loading images by default to improve Core Web Vitals.
Syntax
tsx
import Image from 'next/image';
import profilePic from '../public/me.png'; // Local image import
export default function Profile() {
return (
<div>
{/* Local Images: Next.js reads dimensions automatically */}
<Image
src={profilePic}
alt="Picture of the author"
placeholder="blur" // Auto blur-up while loading
/>
{/* Remote Images: Require explicit width/height to prevent layout shift */}
<Image
src="https://example.com/remote-image.jpg"
alt="Remote image"
width={500}
height={300}
priority // Add this for hero images to load them immediately
/>
</div>
);
}Common Pitfalls
- Failing to provide `width` and `height` (or `fill`) for remote images will result in a runtime error.
- The `priority` prop should only be used for the Largest Contentful Paint (LCP) image on a page (usually the hero image). Don't use it on every image.
Real-World Example
Configuring remote domains to allow external images:
example
tsx
// next.config.ts
// Security: You must explicitly define which external domains are allowed
// to be optimized by the Next.js Image Optimization API.
const nextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
port: '',
pathname: '/**',
},
{
protocol: 'https',
hostname: 'avatars.githubusercontent.com',
},
],
},
};
export default nextConfig;