🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

next/image: Responsive, Lazy-Loaded Images Done Right

Next.js PerformanceđŸŸĸ Free Lesson

next/image: Responsive, Lazy-Loaded Images Done Right

A page is often mostly images, and images are usually where performance budgets die. The browser downloads oversized files, decodes them on the main thread, and shifts content around as dimensions resolve. Next.js ships an Image component that attacks all three problems: it serves modern formats, generates a srcSet for responsive widths, sizes lazy-loading by default, and reserves layout space from the intrinsic dimensions you provide. Used correctly it can cut image bytes by half or more with no redesign; used carelessly it can produce blurry hero art, 400 errors from remote hosts, and a largest-contentful-paint that still misses the budget.

This lesson goes through the component's props as a system, the configuration that controls formats and remote domains, the layout techniques that eliminate shift, and the priority rules that protect the element above the fold.

Prerequisites

  • !Next.js project structure and components
  • !HTML image basics: alt, width, height, and srcset concepts
  • !Understanding of Core Web Vitals at a surface level

What You'll Learn

  • 1Choose fill versus fixed sizing for each image context
  • 2Configure remotePatterns and deviceSizes for real traffic
  • 3Eliminate cumulative layout shift with aspect ratios and placeholders
  • 4Apply priority only where it belongs

Fixed dimensions and the width-height contract

The simplest usage is an image with known intrinsic size. Passing width and height does not force those rendered pixels; it gives the browser the aspect ratio it needs to reserve space before the file downloads, which is what keeps layout shift near zero.

// components/avatar.jsx
import Image from 'next/image';

export default function Avatar({ src, name }) {
  return (
    <Image
      src={src}
      alt={`Portrait of ${name}`}
      width={96}
      height={96}
      className="rounded-full"
    />
  );
}

The alt text is not optional decoration. It is how screen readers announce the image and how image search understands context. Write a description of the content; use an empty alt only for genuinely decorative images that add nothing to the meaning of the page. Browsers also use the ratio implied by width and height to reserve space even before CSS loads, which keeps the pre-hydration layout stable.

Fill mode for containers you do not control

Hero banners, card backgrounds, and gallery tiles live inside a positioned parent rather than a fixed box. The fill prop switches the image to absolute positioning inside that parent, and sizes tells the browser which rendered width to expect at each viewport so it downloads the smallest adequate file.

// components/hero.jsx
import Image from 'next/image';

export default function Hero({ src }) {
  return (
    <div className="relative h-[420px] w-full overflow-hidden rounded-3xl">
      <Image
        src={src}
        alt="Team collaborating around a desk"
        fill
        sizes="(max-width: 768px) 100vw, 1200px"
        priority
        className="object-cover"
      />
      <div className="absolute inset-0 bg-gradient-to-t from-black/60" />
      <h1 className="absolute bottom-8 left-8 text-white">Ship faster together</h1>
    </div>
  );
}

Getting sizes wrong is the most expensive mistake in this component. A generic 100vw on a desktop layout makes the browser fetch the 1920-pixel variant for a slot that is actually 600 pixels wide. Describe the real rendered widths; the bandwidth waste is silent, and the only visible symptom is a heavier network panel.

Formats, quality, and the image loader

The default loader converts source files to WebP or AVIF at request time and serves them from /_next/image with caching headers. You influence output through next.config: imageSizes controls the generated widths for fixed images, deviceSizes covers viewport-relative ones, formats decides which modern formats are offered, and qualities trims the quality ladder. Remote sources must be allowlisted, or every request returns a 400 — a deliberate security measure so the endpoint cannot be used as an open image proxy.

javascript
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    formats: ['image/avif', 'image/webp'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
    qualities: [60, 75, 90],
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'cdn.example.com',
        pathname: '/assets/**',
      },
      {
        protocol: 'https',
        hostname: 'images.unsplash.com',
      },
    ],
  },
};

export default nextConfig;

Scope remote patterns as tightly as the protocol and hostname allow. A wildcard hostname turns your optimization endpoint into a bandwidth amplifier for anyone who finds it.

Placeholders and progressive loading

A blank rectangle while an image loads is a poor experience on slow connections. The placeholder="blur" prop shows a low-quality image until the real one arrives, fed either by a tiny inline data URL or by an imported static file.

// components/product-shot.jsx
import Image from 'next/image';
import placeholder from './blur-dataurl';

export default function ProductShot({ src, alt }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={800}
      height={600}
      placeholder="blur"
      blurDataURL={placeholder}
    />
  );
}

For remote images, provide a small blurred data URL manually — Next.js cannot generate a blur placeholder from an off-site URL at runtime without fetching it, and doing so on every render would defeat the caching.

Lazy loading and priority

Everything is lazy by default: images below the fold download when the browser's intersection observer says they are approaching the viewport. The hero image is the exception. As the largest contentful paint element on many pages, it should be discovered immediately, which is what priority signals — it preloads the image and disables lazy loading for that instance.

// A marketing page: one priority hero, everything else lazy
export default function LandingPage() {
  return (
    <main>
      <Image src="/hero.jpg" alt="Product overview" width={1600} height={900} priority />

      <section className="grid gap-6 md:grid-cols-3">
        <Image src="/feature-1.jpg" alt="Reports dashboard" width={640} height={400} />
        <Image src="/feature-2.jpg" alt="Team permissions screen" width={640} height={400} />
        <Image src="/feature-3.jpg" alt="Mobile companion app" width={640} height={400} />
      </section>
    </main>
  );
}

Marking every image priority is worse than marking none: the preload queue floods, critical CSS and font competition increases, and the hero no longer gets its head start. One or two priority images per route is the norm.

Performance metrics this actually moves

LeverMetric affectedTypical impact
WebP or AVIF outputLCP, total bytes30 to 70 percent smaller than JPEG
Correct sizesLCP, bandwidthAvoids 2 to 4 times over-fetch on desktop
Width and height ratioCLSRemoves most image-induced shift
Lazy loading below foldTBT, bandwidthDefers offscreen downloads entirely
Priority on the heroLCPOften hundreds of milliseconds earlier

Production pitfalls

The field reports repeat: sizes set to 100vw everywhere, so desktop users download mobile-hosted 1920-pixel images that render in a 400-pixel slot. Remote image domains missing from remotePatterns after a CDN migration, producing a wall of 400s only in production. AVIF enabled globally, which helps modern browsers and punishes older ones behind the same URL without a fallback ladder. And priority applied to every image in a loop because it "feels faster", which measurably hurts the metric it was meant to help.

Inside the optimization endpoint

Understanding what happens between your JSX and the bytes on the wire makes the configuration options less mysterious. When a request hits /_next/image, the optimizer checks the allowlist, resolves the source — local file or remote fetch — and caches the result keyed by source URL, width, quality, and format. Local images under the project directory are read from disk; remote ones are fetched once, stored, and re-served until their cache expires, which is why a CDN migration should include a plan for purging or renaming optimized URLs. The width comes from the sizes and deviceSizes ladders: the browser requests an entry close to its rendered need, and the optimizer generates that variant once for all users. Quality defaults are sensible, but product photography with fine gradients sometimes improves noticeably at a higher setting while icons and screenshots degrade invisibly at a lower one. Knowing the cache is keyed by these parameters also explains why two components displaying the same file at different qualities download different bytes — and why tuning one image's quality has no side effects on the rest of the site.

Common Mistakes

Writing sizes="100vw" on images that render in a column

Fix: Match sizes to the actual rendered width at each breakpoint, for example (max-width: 768px) 100vw, 400px.

Omitting alt text to move faster

Fix: Every meaningful image needs descriptive alt; reserve empty alt only for decorative imagery.

Allowlisting an entire CDN hostname with a wildcard path

Fix: Restrict pathname patterns to the directories you actually serve images from.

Setting priority on every image in a list

Fix: Reserve priority for the largest contentful paint element; let everything else lazy-load.

Best Practices

  • Audit the network panel on a real device and fix the worst oversized images first
  • Keep intrinsic dimensions on every image, including those in cards and galleries
  • Serve AVIF with WebP fallback through the built-in formats ladder
  • Pair fill images with an aspect-ratio parent so CLS stays at zero

Interview Questions

Q1: Why does the Image component need width and height if CSS controls the visual size?

They communicate the intrinsic aspect ratio so the browser reserves layout space before the file loads, preventing cumulative layout shift.

Q2: What happens when a remote image host is not in remotePatterns?

The optimization endpoint rejects the request with a 400; the allowlist exists so the endpoint cannot act as a general-purpose open image proxy.

Q3: When should priority be used?

Only on images likely to be the largest contentful paint element — typically the hero — so they preload immediately while everything else stays lazy.

Key Takeaways

  • next/image gives modern formats, responsive srcSet generation, lazy loading, and reserved layout space by default.
  • Fixed sizing uses width and height; fill mode needs a positioned parent and an accurate sizes attribute.
  • Allowlist remote hosts tightly in remotePatterns to keep the optimizer safe and predictable.
  • Blur placeholders and correct sizes attributes shape the perceived experience more than raw pixel counts.
  • Priority is a scarce resource: spend it on the hero, not the gallery.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement