How to Optimize Nextjs Images

How to Optimize Next.js Images Image optimization is one of the most impactful ways to improve website performance, user experience, and search engine rankings. In modern web development, Next.js has emerged as a leading framework for building fast, scalable, and SEO-friendly applications. One of its most powerful built-in features is the next/image component, designed specifically to handle image

Nov 10, 2025 - 08:38
Nov 10, 2025 - 08:38
 1

How to Optimize Next.js Images

Image optimization is one of the most impactful ways to improve website performance, user experience, and search engine rankings. In modern web development, Next.js has emerged as a leading framework for building fast, scalable, and SEO-friendly applications. One of its most powerful built-in features is the next/image component, designed specifically to handle image optimization automatically. However, many developers underutilize its full potential or misconfigure it, leading to slower load times, higher bandwidth usage, and missed SEO opportunities.

This comprehensive guide walks you through every aspect of optimizing images in Next.jsfrom basic setup to advanced techniques. Whether you're building an e-commerce site, a blog, or a corporate landing page, mastering Next.js image optimization will help you achieve faster Core Web Vitals, better Google rankings, and higher conversion rates. By the end of this tutorial, youll know how to implement responsive images, leverage modern formats, avoid common pitfalls, and use tools to validate your results.

Step-by-Step Guide

1. Understand the next/image Component

Next.js provides a built-in next/image component that replaces the standard HTML <img> tag. This component automatically handles critical optimization tasks such as:

  • Lazy loading images
  • Resizing images to match the display size
  • Converting images to modern formats like WebP and AVIF
  • Generating multiple image variants for different screen densities
  • Using a Content Delivery Network (CDN) for faster delivery
  • Preloading above-the-fold images

To use it, first import the component:

import Image from 'next/image';

Then replace your standard <img> tags with the <Image> component:

<Image

src="/images/my-photo.jpg"

alt="A description of the image"

width={500}

height={300}

/>

Notice that unlike the native <img> tag, <Image> requires explicit width and height properties. This is criticalit enables Next.js to reserve space during rendering, preventing layout shifts (CLS), which negatively impact user experience and SEO scores.

2. Configure Image Optimization in next.config.js

By default, Next.js uses its own image optimization service, which works out of the box for local development and deployments on Vercel. However, if youre deploying elsewhere (e.g., Netlify, AWS, or a custom server), you must configure the images domain in next.config.js.

Open your next.config.js file and add the following configuration:

/** @type {import('next').NextConfig} */

const nextConfig = {

images: {

domains: ['example.com', 'cdn.yoursite.com', 'images.unsplash.com'],

formats: ['image/webp', 'image/avif'],

deviceSizes: [640, 768, 1024, 1280, 1536],

imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],

minimumCacheTTL: 60,

},

};

module.exports = nextConfig;

Lets break down each option:

  • domains: Lists all external domains from which you load images. If youre pulling images from Unsplash, Cloudinary, or a CMS, add their domains here. Missing domains will cause images to fail to load.
  • formats: Specifies which image formats to generate. WebP is widely supported; AVIF offers better compression but has limited browser support. Including both ensures maximum compatibility and performance.
  • deviceSizes: Defines the width breakpoints for responsive images. These should match your CSS breakpoints (e.g., mobile, tablet, desktop).
  • imageSizes: Defines sizes for images used in non-responsive contexts (e.g., icons or avatars).
  • minimumCacheTTL: Sets the minimum time (in seconds) images are cached. Increase this for static assets to reduce origin server load.

Always validate your configuration by checking the network tab in your browsers DevTools. You should see URLs like /_next/image?url=...&w=1200&q=75, indicating Next.js is processing your images.

3. Use External Image Sources Correctly

Many Next.js applications pull images from external sources like CMS platforms (Contentful, Sanity, WordPress), e-commerce systems (Shopify), or stock photo services (Unsplash). To ensure these images are optimized, you must explicitly allow their domains in the images.domains array.

For example, if you're using Cloudinary:

images: {

domains: ['res.cloudinary.com'],

},

Then use the full URL in your Image component:

<Image

src="https://res.cloudinary.com/your-account/image/upload/v1600000000/photo.jpg"

alt="Cloudinary image"

width={800}

height={600}

/>

Important: Never use relative paths for external images. Always use absolute URLs. Also, avoid using unoptimized={true} unless you have a specific reason (e.g., using a third-party image service that already optimizes images).

4. Implement Responsive Images with Layout Props

The layout prop in <Image> controls how the image scales within its container. The three most common values are:

  • intrinsic: The image scales down but never exceeds its original size. Best for images with fixed dimensions (e.g., product photos).
  • responsive: The image scales to fill its container, maintaining aspect ratio. Ideal for hero banners or dynamic layouts.
  • fill: The image fills its parent container entirely. Requires the parent to have position: relative. Use this for full-width banners or background images.

Example with layout="responsive":

<div style={{ width: '100%', maxWidth: '1200px', margin: '0 auto' }}>

<Image

src="/images/hero-banner.jpg"

alt="Hero banner"

width={1200}

height={600}

layout="responsive"

/>

</div>

Example with layout="fill":

<div style={{ position: 'relative', width: '100%', height: '400px' }}>

<Image

src="/images/background.jpg"

alt="Background image"

fill

style={{ objectFit: 'cover' }}

/>

</div>

Always pair fill with objectFit (e.g., cover, contain) to control how the image fits within its container.

5. Optimize Image Quality and Format

By default, Next.js compresses images to 75% quality. While this is a good balance, you can adjust it based on your needs:

<Image

src="/images/product.jpg"

alt="Product image"

width={500}

height={500}

quality={85}

/>

Higher quality (e.g., 8590) is suitable for product galleries or high-detail photography. Lower quality (e.g., 6070) works for thumbnails or decorative images.

Next.js automatically converts images to WebP and AVIF if supported by the browser. To verify this, inspect the network tab in Chrome DevTools. You should see image/webp or image/avif in the Content-Type header.

If you want to force a specific format (e.g., for testing), you can use the priority and fetchPriority props:

<Image

src="/images/logo.png"

alt="Logo"

width={200}

height={100}

priority

fetchPriority="high"

/>

priority preloads the image, useful for above-the-fold content. fetchPriority tells the browser to prioritize fetching this image over others.

6. Lazy Loading and Preloading Strategy

Next.js automatically lazy loads images below the fold. But you can fine-tune this behavior:

  • Use priority={true} for critical images (e.g., hero banners, logos, above-the-fold product images).
  • Leave priority as false (default) for images that appear after scrolling.

For even better performance, preload key images in your _document.js file:

import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {

return (

<Html>

<Head>

<link

rel="preload"

as="image"

href="/images/hero-banner.webp"

type="image/webp"

/>

</Head>

<body>

<Main />

<NextScript />

</body>

</Html>

);

}

This ensures the browser starts downloading critical images as early as possible, reducing perceived load time.

7. Use Placeholder Images for Better UX

Next.js supports blur-up and transparent placeholders to improve perceived performance:

<Image

src="/images/photo.jpg"

alt="A beautiful landscape"

width={800}

height={600}

placeholder="blur"

blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD..."

/>

The blurDataURL property accepts a base64-encoded low-resolution version of the image. You can generate this automatically using tools like BlurHash or manually with image editors.

Alternatively, use placeholder="empty" for a transparent placeholder or omit it entirely for no placeholder.

Blur placeholders reduce visual jank and make the page feel faster, even before the full image loads.

8. Avoid Common Pitfalls

Here are the most common mistakes developers make when optimizing images in Next.js:

  • Missing width and height: This causes layout shifts and poor Core Web Vitals scores.
  • Using large source images: Never upload 5MB JPEGs. Resize and compress images before uploading.
  • Forgetting to add external domains: Images from CDNs or CMS will break silently.
  • Using unoptimized={true} unnecessarily: This disables all optimizations. Only use it if youre using a third-party service that already optimizes images (e.g., Cloudinary with automatic format conversion).
  • Not testing on mobile: Always check image performance on slower networks and smaller screens using Chrome DevTools Network Throttling and Device Mode.

Best Practices

1. Always Resize Images Before Uploading

While Next.js resizes images on-the-fly, its inefficient to serve a 4000px-wide image to a mobile device. Always pre-process your images:

  • Use tools like Photoshop, Affinity Photo, or free alternatives like GIMP or Photopea.
  • Export images at the maximum size theyll be displayed (e.g., 1200px wide for desktop, 600px for mobile).
  • Save as WebP first, then fallback to JPEG if needed.

Pre-resizing reduces server load and speeds up the optimization pipeline.

2. Use Modern Image Formats

WebP reduces file size by 2535% compared to JPEG with identical quality. AVIF offers up to 50% better compression than WebP but has limited support in older browsers.

Next.js automatically serves the best format based on browser support. To ensure maximum compatibility:

  • Always provide images in WebP format as your primary source.
  • Use the format option in next.config.js to include AVIF if your audience uses modern browsers.
  • For older browsers (e.g., Safari 14 or earlier), Next.js will fall back to JPEG or PNG.

3. Implement Proper Alt Text

Alt text is not just for accessibilityits critical for SEO. Search engines use alt text to understand image content and rank your pages in image search results.

Best practices:

  • Be descriptive but concise: Red leather womens handbag with gold zipper instead of bag.
  • Include keywords naturally, but avoid keyword stuffing.
  • Never leave alt empty unless the image is purely decorative. In that case, use alt="".

4. Optimize for Core Web Vitals

Image optimization directly impacts three Core Web Vitals:

  • Largest Contentful Paint (LCP): Optimize above-the-fold images with priority={true} and preload them.
  • First Input Delay (FID): Reduce image size and avoid blocking JavaScript to improve interactivity.
  • Cumulative Layout Shift (CLS): Always define width and height to prevent layout shifts.

Use Googles PageSpeed Insights or Lighthouse to audit your pages. Aim for LCP under 2.5 seconds and CLS under 0.1.

5. Leverage CDN and Edge Caching

Next.js image optimization is handled by a built-in image CDN. When deployed on Vercel, this CDN is global and highly optimized. If youre using another host (e.g., Netlify, AWS), consider using a third-party image CDN like Cloudinary, Imgix, or ImageKit to offload optimization and caching.

These services offer:

  • Automatic format conversion
  • Intelligent compression
  • Real-time resizing
  • Advanced caching rules

For example, with Cloudinary, you can use dynamic URLs like:

https://res.cloudinary.com/your-account/image/upload/w_800,q_80,f_webp/photo.jpg

And configure Next.js to use it with domains: ['res.cloudinary.com'] and unoptimized={true}.

6. Monitor Performance Regularly

Image optimization isnt a one-time task. As your content grows, so does your image library. Set up monitoring:

  • Use Lighthouse CI to run performance audits on every PR.
  • Integrate with Google Search Console to track image indexing and performance.
  • Set up alerts for large image uploads via your CMS or CI/CD pipeline.

7. Use SVG for Icons and Logos

Vector graphics like logos, icons, and illustrations should always be served as SVG files. Theyre resolution-independent, lightweight, and scalable.

Next.js supports SVG imports directly:

import Logo from '../public/logo.svg';

<Logo width={200} height={50} />

Or use inline SVGs for maximum control and performance:

<svg width="200" height="50" viewBox="0 0 200 50" xmlns="http://www.w3.org/2000/svg">

<path d="..." fill="currentColor"/>

</svg>

Inline SVGs eliminate HTTP requests and can be styled with CSS.

Tools and Resources

1. Image Compression Tools

  • Squoosh Free, open-source tool by Google for comparing compression formats and adjusting quality.
  • TinyPNG Excellent for batch compressing PNG and JPEG files.
  • ImageOptim Mac app that strips metadata and optimizes PNG, JPEG, and GIF files.
  • GraphicsMagick Command-line tool for bulk image processing in automation workflows.

2. Blur Hash Generation

  • BlurHash Generate blur-up placeholders using a simple algorithm. Next.js supports BlurHash natively.
  • blurhash JavaScript library to encode/decode BlurHash strings.

3. Performance Auditing

4. Image CDNs

  • Cloudinary Full-service image and video platform with automatic optimization.
  • Imgix Real-time image processing with advanced format and quality controls.
  • ImageKit Affordable, developer-friendly image CDN with Next.js integration.
  • MaxCDN (StackPath) Includes image optimization as part of its CDN suite.

5. Next.js Image Optimization Plugins

Real Examples

Example 1: E-Commerce Product Gallery

Consider an e-commerce site selling clothing. Each product has 58 images. Without optimization, page load times exceed 5 seconds.

Before Optimization:

  • Images: 24 MB JPEGs
  • No width/height specified
  • Loaded with standard <img> tags
  • No lazy loading

After Optimization:

  • Images resized to 1200px width, converted to WebP (avg. 200 KB each)
  • Used <Image> with width, height, and layout="responsive"
  • Set priority={true} for the main product image
  • Used placeholder="blur" with BlurHash for thumbnails
  • Added alt text with product name and color

Result: LCP improved from 5.2s to 1.8s. Page size reduced by 78%. Mobile bounce rate dropped by 32%.

Example 2: Blog with User-Generated Images

A content site allows authors to upload images via a CMS. Many upload 5MB photos from smartphones.

Solution:

  • Configured next.config.js with domains: ['cdn.yourcms.com']
  • Used next/image with quality={70} for all images
  • Added a pre-upload validation step in the CMS to reject images over 2MB
  • Automatically converted uploads to WebP on the CMS side

Result: Average image size dropped from 3.2MB to 280KB. Server bandwidth costs reduced by 85%. Google Lighthouse score improved from 62 to 94.

Example 3: Travel Blog with Hero Banners

Each blog post has a full-width hero banner. Originally used a 4000px-wide image with no responsive handling.

Optimization:

  • Created 3 versions: 640px (mobile), 1024px (tablet), 1920px (desktop)
  • Used layout="fill" with parent container set to position: relative
  • Added priority={true} and fetchPriority="high"
  • Preloaded the hero image in _document.js

Result: Hero image loaded 2.1 seconds faster. CLS score improved from 0.3 to 0.02. Googles mobile speed score jumped from 45 to 89.

FAQs

Do I need to install any packages to use next/image?

No. The next/image component is built into Next.js v10 and later. No additional installation is required.

Why do I need to specify width and height?

Specifying width and height allows Next.js to calculate the aspect ratio and reserve space during rendering. This prevents layout shifts, which hurt user experience and SEO.

Can I use next/image with dynamic image URLs?

Yes. You can use dynamic paths like src={/images/${product.id}.jpg}. Just ensure the domain is allowed in next.config.js if the URL is external.

What happens if I dont add external domains to next.config.js?

Images from external domains will not be optimized and may fail to load. Next.js will throw a warning in the console during development and block the image in production.

Does next/image work with SVG files?

No. The next/image component is designed for raster images (JPEG, PNG, WebP, AVIF). Use native SVG imports or inline SVG for vector graphics.

How can I test if my images are being optimized?

Open Chrome DevTools ? Network tab ? Filter by Img. Look for URLs containing /_next/image. Check the Content-Type header: it should say image/webp or image/avif.

Can I disable image optimization?

Yes, by setting unoptimized={true}. Only do this if youre using a third-party service like Cloudinary that already handles optimization.

Is AVIF better than WebP?

Yes, AVIF offers superior compression and quality. However, browser support is still growing. Use both formats for maximum compatibility.

How do I handle animated GIFs?

Next.js does not optimize animated GIFs. Convert them to MP4 or WebP animations for better performance. Use the HTML <video> tag with autoplay and loop for animated content.

Whats the best way to optimize images for SEO?

Combine proper file naming, descriptive alt text, responsive sizing, fast loading, and inclusion in your sitemap. Use schema.org markup for product images if applicable.

Conclusion

Optimizing images in Next.js is not just a performance tweakits a fundamental requirement for modern web applications. With the built-in next/image component, Next.js provides one of the most powerful and developer-friendly image optimization systems available today. But its power lies in proper configuration and consistent usage.

By following the steps in this guideconfiguring domains, using correct dimensions, leveraging modern formats, implementing placeholders, and auditing performanceyou can transform slow, bloated image-heavy pages into lightning-fast, SEO-optimized experiences.

Remember: every millisecond counts. A 1-second delay in page load can reduce conversions by 7%. Optimized images dont just make your site look betterthey make it work better, rank higher, and convert more.

Start small: pick one page with heavy images, apply these techniques, measure the results, and scale across your site. Over time, youll build a performant, scalable, and user-friendly image strategy that sets your Next.js application apart.

Dont wait for users to complain about slow loading. Optimize proactivelyand watch your Core Web Vitals, rankings, and engagement metrics soar.