Optimizing images

Intermediate · 9 min

Use next/image for correctly sized, lazy-loaded images with no layout shift, and configure remote images, sizes, quality, and preloading in Next.js 16.

Before thisPages and layouts

leerob · 9 min

Optimizing images

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by leerobReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `<Image>` extends `<img>` to serve correctly sized images in modern formats, reserve space to prevent layout shift, lazy-load by default, and resize on demand, including for remote images.
  • `width` and `height` are the image's intrinsic size, used for aspect ratio; CSS still controls the rendered size. They are required unless the image is statically imported or uses `fill`.
  • Remote images need a `remotePatterns` entry in `next.config` that is as specific as possible, because Next.js will optimize only what you allow.
  • With `fill` or a responsive layout, set `sizes`; without it the browser assumes the image is the full viewport wide and may download far too much.
  • In Next.js 16 the `priority` prop is deprecated: use `preload` for a known LCP image, or `loading="eager"` to just disable lazy loading, and `qualities` now defaults to `[75]`.

Images are usually the heaviest thing on the page

A plain <img src="/photo.jpg"> ships whatever file you gave it. A 4000-pixel photo goes to a phone that shows it 360 pixels wide. The page has no idea how tall the image is until it arrives, so text jumps when it loads. Every image downloads even if it is far below the fold.

Fixing each of these by hand is real work: resize to several widths, write a srcset, pick formats, add dimensions, set lazy loading. The <Image> component from next/image does that for you. The docs list what it adds to <img>:

  • Size optimization: correctly sized images for each device, in modern formats like WebP.
  • Visual stability: layout shift is prevented while images load.
  • Faster loads: images load when they enter the viewport using native lazy loading, with optional blur-up placeholders.
  • Flexibility: images are resized on demand, even remote ones.

The related css roadmap lesson on sizing images and replaced elements explains the layout side.

Local images

Files in public are served from /. Give <Image> the path and the intrinsic size:

import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="Picture of the author"
      width={500}
      height={500}
    />
  )
}

alt is required. width and height are the image’s intrinsic size in pixels. They give the browser an aspect ratio so it can reserve the space. They do not set the rendered size, which stays under CSS control.

If you import the file instead, Next.js reads the size itself:

import ProfileImage from './profile.png'

<Image src={ProfileImage} alt="Picture of the author" placeholder="blur" />

A static import also provides blurDataURL, so placeholder="blur" works with no extra data. A static import also lets the image be hashed and cached with a long-lived immutable header, which is why the docs suggest it over tuning minimumCacheTTL. When you cannot import, a dynamic import() in a Server Component gives the same width, height and blur data, as long as the path has a static prefix like ../content/blog/images/.

Remote images

For a remote image, pass a URL string and give width and height yourself. Next.js cannot see the file at build time, so it cannot know the size. If you do not know the size, use fill.

Next.js will also not optimize arbitrary hosts. You allow them in next.config:

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

const config: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 's3.amazonaws.com',
        port: '',
        pathname: '/my-bucket/**',
        search: '',
      },
    ],
  },
}

export default config

Be as specific as you can, as the docs say, to prevent malicious use. This allows one bucket on one host, not all of S3. There is a similar localPatterns option to restrict which local paths may be optimized.

Responsive images: fill and sizes

With fill, the image expands to its parent. The parent must be positioned (relative, fixed, or absolute), and you control cropping with object-fit.

<div className="grid-element">
  <Image
    fill
    src="/example.png"
    alt="Example"
    sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  />
</div>

sizes tells the browser how wide the image will be, so it can choose from the srcset Next.js generates. The docs say to use it with fill and when CSS makes the image responsive. Leave it out and the browser assumes 100vw. How srcset is built depends on it too: with no sizes on a fixed-width image you get a small 1x/2x set, with no sizes on a fill image you get one built from deviceSizes as if the image spans the viewport, and with sizes you get the full set of widths.

Quality and formats

quality is 1 to 100 and defaults to 75. In Next.js 16 you need to allow the values you use: images.qualities is required and defaults to [75]. A value outside the list is coerced to the nearest allowed one, so with qualities: [50, 75, 100], quality={80} is served as 75, and development warns you. The docs explain the reason: unrestricted access could let someone ask for more qualities than you intended.

Formats are chosen from the request’s Accept header against the configured formats, which defaults to ['image/webp']. You can add 'image/avif' ahead of WebP; the docs note that each format is cached separately, so storage grows.

The hero image, in Next.js 16

The image above the fold should not be lazy-loaded, and if it is the Largest Contentful Paint element the browser should start fetching it early. The old way was priority. In 16 it is deprecated:

  • preload inserts a preload link in the <head>. Use it for a known LCP image.
  • loading="eager" disables lazy loading. The docs say this is the right choice in most cases for an above-the-fold image, optionally with fetchPriority="high".

Do not use preload when several images could be the LCP depending on viewport, or when you already use loading or fetchPriority. The consequences for the metric are in core web vitals in Next.js.

What the video covers

Lee Robinson’s video is from June 2023, about nine minutes, and the official Image docs link to it. Per its title and the chapters recorded when it was sourced, it covers remote images, fill, sizes, responsive images, and loaders. We could not read a transcript. It predates Next.js 16, so it shows priority and does not cover the qualities allowlist or localPatterns; the sections above replace those. The runner-up, Dave Gray’s 2023 video, goes deeper on sizes, priority, and layout shift.

Where this fits

Local files, remote hosts, fonts and images are now handled. The last asset type is code that is not yours. Next: scripts and third-party code.

Check yourself

  1. 01Why does `<Image>` need a `width` and `height` for a remote image but not for a statically imported one?

    Next.js cannot read a remote file at build time, so it needs the intrinsic size to infer an aspect ratio and avoid layout shift. For a static import it reads the dimensions itself. `fill` is the alternative when sizes are unknown.

  2. 02What does `sizes` do, and what happens if you leave it out on a `fill` image?

    It tells the browser how wide the image will be at different breakpoints so it picks a suitable file from the generated `srcset`. Without it the browser assumes `100vw`, and Next.js generates a `srcset` as if the image spans the viewport, which can download an unnecessarily large file.

  3. 03You are loading images from an S3 bucket. What must you add, and how specific should it be?

    Add a `remotePatterns` entry under `images` in `next.config`, with protocol, hostname, and a pathname limited to the bucket. The docs say to be as specific as possible to prevent malicious use.

  4. 04How did marking a hero image as important change in Next.js 16?

    `priority` is deprecated. Use `preload` to keep the same behavior of inserting a preload link in the head, or `loading="eager"` if you only need to turn off lazy loading.

  5. 05When should you not use `preload`?

    When several images could be the LCP element depending on viewport, and when you already use `loading` or `fetchPriority` on the image.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark