How to Optimize Nextjs Images

Introduction Optimizing images in Next.js applications is a crucial step in improving website performance, user experience, and search engine rankings. Images often constitute a significant portion of a webpage’s total size, affecting page load speed and responsiveness. Next.js, a popular React framework, provides built-in features and tools specifically designed to handle image optimization effic

Nov 17, 2025 - 11:16
Nov 17, 2025 - 11:16
 0

Introduction

Optimizing images in Next.js applications is a crucial step in improving website performance, user experience, and search engine rankings. Images often constitute a significant portion of a webpage’s total size, affecting page load speed and responsiveness. Next.js, a popular React framework, provides built-in features and tools specifically designed to handle image optimization efficiently. This tutorial will guide you through the process of optimizing images in Next.js, demonstrating why it is important and how to implement best practices to ensure your site loads quickly and looks great across all devices.

Step-by-Step Guide

1. Setting Up Your Next.js Project

If you haven’t already, start by creating a new Next.js project. You can do this easily using the following command:

npx create-next-app@latest my-nextjs-app

Navigate to your project folder:

cd my-nextjs-app

Ensure you have the latest Next.js version installed to take advantage of the most recent image optimization features.

2. Using the Built-In <Image> Component

Next.js provides a built-in <Image> component that automatically optimizes images on-demand. It supports lazy loading, resizing, and serving modern formats like WebP. To use it, import the component:

import Image from 'next/image'

Example usage:

<Image src="/images/sample.jpg" alt="Sample" width={600} height={400} />

Key points:

  • src: Path or URL to the image.
  • width and height: Required to avoid layout shifts and improve CLS (Cumulative Layout Shift).
  • alt: Important for accessibility and SEO.

3. Configuring next.config.js for Remote Images

If you need to optimize images hosted on external domains, you must configure the next.config.js file:

module.exports = {

  images: {

    domains: ['example.com', 'another-domain.com'],

  },

};

This allows Next.js to optimize and serve remote images securely.

4. Leveraging Image Placeholders

Next.js supports placeholder images to improve perceived loading times. You can use the placeholder prop with values like 'blur':

<Image src="/images/sample.jpg" alt="Sample" width={600} height={400} placeholder="blur" blurDataURL="/images/sample-blur.jpg" />

This provides a low-quality blurred image while the main image loads, enhancing user experience.

5. Using Responsive Images

The <Image> component supports responsive images via the sizes property:

<Image

  src="/images/sample.jpg"

  alt="Sample"

  width={1200}

  height={800}

  sizes="(max-width: 600px) 480px, 800px"

/>

This instructs the browser to select the appropriate image size based on the viewport width, reducing unnecessary data usage.

6. Optimizing Static Images

Next.js automatically optimizes images in the public folder when used with the <Image> component. For build-time optimization, you can integrate tools like sharp to preprocess images before deployment, ensuring faster loading without runtime overhead.

7. Customizing Image Loaders

Next.js allows defining custom image loaders for special use cases, such as integrating with CDNs:

const myLoader = ({ src, width, quality }) => {

  return https://example-cdn.com/${src}?w=${width}&q=${quality || 75};

};

<Image loader={myLoader} src="photo.jpg" alt="Photo" width={700} height={475} />

This is useful for advanced optimization strategies.

8. Implementing Lazy Loading

Lazy loading defers loading images until they are close to entering the viewport. The Next.js <Image> component enables lazy loading by default, but it can be controlled manually with the loading attribute:

<Image src="/images/sample.jpg" alt="Sample" width={600} height={400} loading="lazy" />

Ensure critical above-the-fold images are loaded eagerly to avoid delays in visible content.

Best Practices

1. Always Specify Width and Height

Defining explicit width and height props prevents layout shifts, improving the Core Web Vitals metric CLS. This leads to better SEO rankings and a smoother user experience.

2. Use Modern Image Formats

Where possible, use modern formats such as WebP or AVIF. These formats offer better compression and quality than traditional JPEG or PNG. Next.js automatically serves WebP when supported by the browser.

3. Optimize Images Before Upload

Reduce image file sizes using tools like ImageOptim, TinyPNG, or SVGO before including them in your project. This reduces build times and improves initial loading speed.

4. Use Responsive Images

Employ the sizes prop to deliver appropriately sized images based on device viewport. This minimizes data usage on mobile devices.

5. Leverage Caching and CDN

Host images on a CDN to speed up delivery globally. Configure caching headers to allow browsers to cache images efficiently, reducing repeat load times.

6. Avoid Inline Base64 Images for Large Assets

While small inline base64 images can improve performance, large base64-encoded images increase HTML size and should be avoided.

7. Monitor Performance Metrics

Regularly check your web performance scores using tools like Google Lighthouse or WebPageTest to identify image-related bottlenecks and optimize accordingly.

Tools and Resources

1. Next.js Documentation

The official Next.js docs provide comprehensive guidance on the <Image> component and image optimization strategies: Next.js Image Optimization

2. Image Compression Tools

  • ImageOptim – Mac app for lossless compression
  • TinyPNG – Online PNG and JPEG compression
  • Squoosh – Browser-based image compression and format conversion

3. CDN Providers

  • Vercel – Next.js creators offering global CDN
  • Cloudinary – Advanced image management and delivery
  • Imgix – Real-time image processing and CDN

4. Performance Testing Tools

Real Examples

Example 1: Simple Local Image Optimization

In this example, a local JPEG image is optimized using the Next.js <Image> component with explicit width and height:

import Image from 'next/image';

export default function Home() {

  return (

    <div>

      <h1>Optimized Local Image</h1>

      <Image src="/images/photo.jpg" alt="Photo" width={800} height={600} placeholder="blur" blurDataURL="/images/photo-blur.jpg" />

    </div>

  );

}

Example 2: Remote Image with Domain Configuration

To serve and optimize a remote image, update next.config.js:

module.exports = {

  images: {

    domains: ['images.unsplash.com'],

  },

};

Then use the <Image> component:

import Image from 'next/image';

export default function Gallery() {

  return (

    <Image

      src="https://images.unsplash.com/photo-1506744038136-46273834b3fb"

      alt="Unsplash Photo"

      width={700}

      height={467}

    />

  );

}

Example 3: Custom Loader with CDN Integration

Using a custom loader to serve images via a CDN:

import Image from 'next/image';

const cdnLoader = ({ src, width, quality }) => {

  return https://cdn.example.com/${src}?w=${width}&q=${quality || 75};

};

export default function Profile() {

  return (

    <Image

      loader={cdnLoader}

      src="avatars/user.png"

      alt="User Avatar"

      width={150}

      height={150}

    />

  );

}

FAQs

What image formats does Next.js support for optimization?

Next.js supports JPEG, PNG, WebP, GIF, SVG, and AVIF formats. It automatically serves the best format supported by the browser, often delivering WebP or AVIF for better compression.

Do I need to install additional packages to use image optimization in Next.js?

No. Image optimization is built-in to Next.js by default. However, for advanced preprocessing or custom loaders, you may need additional tools or dependencies.

Can I optimize images hosted on external servers?

Yes, but you must whitelist the external domains in your next.config.js under the images.domains array.

How does Next.js handle lazy loading?

The Next.js <Image> component lazy loads images by default, improving initial page load speed. You can manually set the loading behavior using the loading prop.

What is the benefit of using the placeholder blur effect?

The placeholder blur effect shows a low-quality version of the image while the full version loads, reducing perceived load time and improving user experience.

Conclusion

Optimizing images in Next.js is essential for delivering fast, responsive, and SEO-friendly websites. Utilizing the built-in <Image> component, configuring remote image domains, leveraging responsive images, and following best practices such as specifying dimensions and using modern formats will significantly enhance your site’s performance. By integrating these strategies, developers can ensure their Next.js applications provide an optimal experience across devices and networks, ultimately contributing to better user engagement and search rankings.