Image Optimization
Automatically optimize images for better performance
🖼️ What is Image Optimization?
Next.js automatically optimizes images for faster loading and better performance. The Image component resizes, optimizes, and serves images in modern formats like WebP automatically without manual configuration.
import Image from 'next/image'
export default function Page() {
return <Image src="/photo.jpg" width={500} height={300} alt="Photo" />
}
Key Image Features
Automatic Optimization
Images are automatically compressed and served in modern formats
Responsive Images
Automatically serves correct size for each device
Priority Loading
Load important images first for better UX
Built-in Security
Prevents image-based attacks automatically
🔹 Basic Image Component
The Next.js Image component provides automatic optimization with simple syntax. Just import the component and specify source, dimensions, and alt text for accessibility.
import Image from 'next/image'
export default function ProfilePage() {
return (
<div>
<h1>User Profile</h1>
<Image
src="/profile.jpg"
width={400}
height={400}
alt="User profile picture"
/>
</div>
)
}
Result:
✅ Image automatically optimized and lazy-loaded
✅ Served in WebP format for modern browsers
✅ Responsive sizing based on device
🔹 Priority Images
Use the priority prop for images that appear above the fold or are critical for Largest Contentful Paint (LCP). This ensures they load immediately without lazy loading.
import Image from 'next/image'
export default function Hero() {
return (
<Image
src="/hero-banner.jpg"
width={1200}
height={600}
alt="Hero banner"
priority
/>
)
}
When to use priority:
- Hero images at the top of the page
- Logo or branding in the header
- Any image visible without scrolling
- Images that affect LCP score
🔹 Fill Container Images
When you don't know image dimensions or want images to fill their container, use the fill prop with proper positioning styles.
import Image from 'next/image'
export default function Card() {
return (
<div style={{ position: 'relative', width: '100%', height: '300px' }}>
<Image
src="/background.jpg"
fill
style={{ objectFit: 'cover' }}
alt="Card background"
/>
</div>
)
}
Result:
✅ Image fills the entire container
✅ Maintains aspect ratio with object-fit
✅ Responsive to container size changes
🔹 Remote Images
To use images from external domains, configure allowed domains in next.config.js for security. This prevents unauthorized image sources from being optimized.
🔸 Configuration
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
},
],
},
}
🔸 Usage
import Image from 'next/image'
export default function Avatar() {
return (
<Image
src="https://example.com/avatar.jpg"
width={100}
height={100}
alt="User avatar"
/>
)
}