Next.js: Optimizing Images with the next/image Component.
Why Use next/image?
Next.js’s <Image> component is a powerful tool that automatically optimizes images for better performance. This includes:
- Lazy loading images (loads only when they come into view).
- Automatically serving the appropriate size for the user’s device.
- Supporting modern image formats like WebP.
This feature is excellent for improving Core Web Vitals, especially Largest Contentful Paint (LCP).
Example: Using the <Image> Component
mport Image from 'next/image';
export default function OptimizedImagePage() {
return (
<div>
<h1>Optimized Images in Next.js</h1>
<Image
src="/images/sample.jpg" // Path to your image
alt="A beautiful scenery"
width={800} // Set width
height={600} // Set height
quality={80} // Optional: Adjust image quality (default: 75)
placeholder="blur" // Optional: Adds a blur effect while loading
/>
</div>
);
}
Key Features of <Image>:
- Automatic Resizing: Generates multiple image sizes for different devices and resolutions.
- Lazy Loading: Reduces the initial page load time by loading images only when needed.
- Placeholder Options:
- placeholder=”blur”: Provides a low-quality image preview (LQIP) while the full image loads.
- You can also add a custom placeholder.
Working with Remote Images
For images hosted on external URLs, configure the next.config.js file to allow those domains:
// next.config.js
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com', // Replace with your domain
pathname: '/images/**', // Match specific paths if needed
},
],
},
};
Then use:
<Image
src="https://example.com/images/sample.jpg"
alt="Remote image"
width={800}
height={600}
/>
Dynamic Images with Responsive Sizing
You can make images responsive by omitting the width and height props and using the layout prop:
<Image
src="/images/sample.jpg"
alt="Responsive image"
layout="responsive"
width={800}
height={600}
/>
This automatically adjusts the image dimensions to fit the container.
Bonus: Image Optimization in Markdown Content
If you’re working with Markdown or CMS content, use the next-mdx-remote library and customize images to be rendered with the <Image> component.
Why This Is a Great Trick
- Performance: Improves page speed by optimizing images automatically.
- SEO: Enhanced performance boosts rankings.
- Ease of Use: No need to manually create multiple image sizes or optimize them before upload.
Mastering the <Image> component is a must for building fast and responsive Next.js apps!
Originally published at https://remejuan.substack.com.
Subscribe there to get all my posts as soon as they are published