Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 72 ยท Optimization and SEO

Image Optimization with next/image

Learn the Next.js Image component: width and height, fill, sizes and srcset, priority loading, remote patterns, formats and how to stop layout shift.

Images are usually the heaviest part of a web page. A single photo straight from a phone can weigh several megabytes, and a page that shows ten of them can feel slow even on a fast connection. Images also cause two of the metrics Google measures: the Largest Contentful Paint (how fast the biggest thing appears) and the Cumulative Layout Shift (how much the page jumps while loading). Getting images right is one of the quickest ways to make a site faster.

Next.js ships a component for this, Image from next/image. It looks like a normal <img>, but it resizes images for each visitor's screen, serves modern formats, loads images lazily, and reserves the right amount of space so nothing jumps. This lesson explains how it works, how to use width, height, fill and sizes, how to treat the first image on a page, and how to allow images from other websites safely.

The real optimizer is part of the Next.js server, which cannot run on this site. The Next.js code is shown read-only, and the two runnable examples are React stand-ins: one rebuilds how srcset and sizes are produced and how a browser picks a file, the other shows how reserving space prevents layout shift. Images in the previews are small inline pictures.

What the component does for you

One component, four jobs

Right size Resizes to the screen, not the original file.
Modern formats WebP by default, AVIF if you enable it.
Lazy loading Images below the fold load when needed.
No layout jump Space is reserved before the file arrives.

You write one tag. The server and browser do the rest.

1 / 2

When the page loads, each <img> points at a URL like /_next/image?url=%2Fteam.jpg&w=1080&q=75. The first time someone asks for that width, the Next.js server fetches the original, resizes it, converts it to a format the browser accepts (it reads the Accept header), stores the result in a cache and sends it. Everyone after that gets the cached file. You keep one big original in your project and never prepare thumbnails by hand.

Basic usage

There are two ways to give Image a source. For a file inside your project, import it. Next.js then knows its dimensions and can even create a blur placeholder:

TSX
import Image from 'next/image';
import team from './team.jpg';

export default function About() {
  return <Image src={team} alt="The whole team at the 2025 offsite" placeholder="blur" />;
}

For a file in the public folder or on another server, pass a string and give the size yourself:

TSX
<Image src="/images/team.jpg" alt="The whole team at the 2025 offsite" width={1200} height={800} />

The alt text is required. Write what the picture shows, or use alt="" when it is only decoration, as you learned in the HTML lessons on images. Everything else you pass, such as className, is forwarded to the <img>.

Why width and height matter

Before an image downloads, the browser does not know how tall it will be. If it guesses zero, the text below sits at the top, and when the file arrives everything is pushed down. That jump is layout shift. Giving the browser width and height lets it calculate the aspect ratio and reserve a box of the right shape immediately. Next.js turns your numbers into the width and height attributes on the <img>, and with a CSS rule such as width: 100%; height: auto the image still scales fluidly while keeping its shape.

Note that width and height here are not the size on screen. They describe the original proportions and the size of the largest version you want. The next example shows the difference, with two cards side by side and a button that "downloads" their images.

Reserved space versus layout shift

Press the button. On the left, the box has no height until the file arrives, so the paragraph jumps down by 150 pixels. On the right, the space was reserved, so nothing moves. That jump is exactly what the layout-shift metric counts. Setting width and height on every image is the whole fix, and it is why the component makes you pass them (or use a static import, which provides them).

Images that fill their parent: fill and sizes

Sometimes you do not know the size ahead of time, for example a card image that stretches to its column, or a hero banner. Use the fill prop instead of width and height. The image then absolutely fills its nearest positioned parent, so that parent must have position: relative (or absolute/fixed) and a size. Control the cropping with CSS object-fit:

TSX
<div style={{ position: 'relative', aspectRatio: '16 / 9' }}>
  <Image
    src="/images/hero.jpg"
    alt="A mountain road at sunrise"
    fill
    sizes="(min-width: 1024px) 50vw, 100vw"
    style={{ objectFit: 'cover' }}
  />
</div>

The sizes prop is the one people skip, and skipping it costs real bandwidth. It tells the browser how wide the image will be on screen at different viewport widths, in the same syntax as the HTML sizes attribute. Here: "on viewports of at least 1024px the image takes half the width, otherwise all of it". Next.js generates a srcset with many widths. The browser reads sizes, works out the slot width, multiplies by the screen's pixel density and downloads the smallest file that is big enough. Without sizes, a fill image is assumed to span the full viewport (100vw), so a phone could download a file meant for a huge desktop banner.

The second example reproduces this logic. It builds the candidate list the way Next.js does (a simplified model of the default deviceSizes and imageSizes), then plays the browser's role. Change the viewport, the pixel density and the sizes value, and see which file is chosen.

srcset and sizes: which file does the browser pick?

With the starting settings (a 1280px desktop with a 2x display and a half-width slot), the slot is 640px, and 2x density means 1,280 device pixels are needed, so the browser takes the 1920 candidate: the smallest one that is wide enough. Press 375px and 1x: the slot is the whole 375px width, and the 384 version is enough. Keep 375px at 2x and the browser asks for 750. Switch to width={400}, no sizes and the list becomes just two entries (1x and 2x), because for a fixed width Next.js uses pixel-density descriptors. Real Next.js has a few more rules than this model, and it lets you change deviceSizes and imageSizes in config. The point stands: sizes is what lets a phone download a small file.

The first image on the page: priority and preload

Images are lazy by default: they load when they get near the viewport. That is right for most images and wrong for the Largest Contentful Paint image, usually a hero photo at the top. For that one, tell Next.js to load it right away with a preload hint:

TSX
<Image src={hero} alt="Spring collection" priority />

priority marks the image as important: it preloads it and turns lazy loading off. In Next.js 16, the newer prop for this is preload, and priority is deprecated but still accepted, so check the docs of your version. Use it for one image per page, typically the one above the fold that is likely to be the largest element. If everything is "priority", nothing is.

Remote images and remotePatterns

An image served from another website needs permission, because the optimizer would otherwise be an open service that anyone could use to resize any file on the internet at your cost. You list allowed sources in next.config.ts:

TypeScript
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'images.example-cdn.com',
        pathname: '/photos/**',
      },
    ],
  },
};

export default nextConfig;

Be as specific as you can: give the protocol, the exact hostname (wildcards like *.example.com exist, use them carefully) and a pathname prefix. A request for any URL that does not match is refused with an error. Local images with a query string need a localPatterns entry in recent versions. Configuring Next.js covers the whole image config.

Formats, quality and caching

TypeScript
images: {
  formats: ['image/avif', 'image/webp'],
  qualities: [60, 75, 85],
  minimumCacheTTL: 60 * 60 * 24, // keep optimized files for a day
},
  • formats lists what the optimizer may produce, in order of preference. The default is WebP only. AVIF files are often smaller but slower to encode, which matters on the first request.
  • qualities limits the allowed quality values, so nobody can request thousands of variants. The default allows 75.
  • minimumCacheTTL sets the minimum time optimized files stay cached. In Next.js 16 the default is four hours; earlier versions used 60 seconds. The longer of this and the original's own Cache-Control is used.

Other details worth knowing: SVG files are not optimized by default (they are already vector, and untrusted SVG can carry scripts, so dangerouslyAllowSVG exists but needs care); animated GIFs are served as they are; and for a static export (output: 'export') there is no server to resize images, so you must use a custom loader or set unoptimized. The server that runs the optimizer needs the sharp library. Next.js installs it for you, but a self-hosted Docker image must keep it (Self-Hosting and Docker).

Finally, remember that Image only handles <img> elements. A picture used as a CSS background-image is not optimized, so for large decorative images, prefer a fill image behind your content.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does next/image ask for width and height (or a static import)?

    The numbers give the aspect ratio. The browser reserves a box of that shape before the file arrives, so content below does not jump.
  2. 2. What does the sizes prop tell the browser?

    sizes describes the on-screen slot. The browser combines it with the pixel density and the srcset widths to download the smallest file that is sharp enough.
  3. 3. A fill image does not show up and has no height. What is the most likely cause?

    A fill image is positioned absolutely inside its nearest positioned parent, so that parent needs position and dimensions.
  4. 4. Which image on a page should get priority (or preload in Next.js 16)?

    Priority is for the LCP candidate. Preloading everything defeats the point and competes for bandwidth.
  5. 5. Why must you list remote hosts in remotePatterns?

    The optimizer fetches and processes the original on your server. An allow-list keeps it from becoming an open image-processing service.

Summary

  • next/image serves resized, modern-format, lazily loaded images through /_next/image, caches the results and reserves layout space.
  • Give every image width and height (or import it statically) to prevent layout shift. Always write meaningful alt text.
  • Use fill with a positioned parent for unknown sizes, and always add sizes so small screens download small files.
  • Mark one above-the-fold image with priority (preload in Next.js 16) and leave the rest lazy.
  • Allow remote images with narrow remotePatterns, and tune formats, qualities and minimumCacheTTL in next.config.ts.
  • SVG and animated GIF are not optimized by default, static exports need a custom loader, and CSS backgrounds bypass the component.

Next: Fonts and Third-Party Scripts