Sitemap

Next.js: Optimizing Images with the next/image Component.

2 min readJan 19, 2025

--

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>:

  1. Automatic Resizing: Generates multiple image sizes for different devices and resolutions.
  2. Lazy Loading: Reduces the initial page load time by loading images only when needed.
  3. 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

  1. Performance: Improves page speed by optimizing images automatically.
  2. SEO: Enhanced performance boosts rankings.
  3. 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

--

--

Reme Le Hane
Reme Le Hane

Written by Reme Le Hane

Runner, Developer, Gamer. | Lead Frontend Engineer at Loop with 14 years Front-End Experience & ~4yrs Flutter. | React Flutter Javascript Dart

No responses yet