WhoBuilt

Using Images in Next.js

Jun 25, 2023· 9 min· 154K views·Watch on YouTube

Lee Robinson, a developer at Vercel, walks through practical Next.js Image component examples in a local demo.

Why use the Image component

The component addresses layout shift, images that are too large for the visitor’s screen or device, and the difficulty of getting images to display as intended. Importing a local image supplies its dimensions automatically, which helps prevent layout shift.

Local and remote image optimization

For a local PNG that is 30.3 KB, the Next.js image route serves an optimized 7.2 KB version in AVIF or WebP in the demo. Remote images also work, but the config must allowlist their domains and URL patterns. Remote images need explicit width and height to prevent layout shift.

Fill, sizes, and image styling

The `fill` prop makes an image occupy its parent instead of using explicit dimensions, and its parent needs positioning and a defined size. With `fill`, the `sizes` prop helps Next.js choose suitable image variations for the viewport. The examples also cover quality, imported-image blur placeholders, and CSS such as `object-fit: cover`.

Responsive grids and custom loaders

A CSS Grid with relatively positioned, 400-pixel-tall parents, `fill`, and `object-fit: cover` creates a responsive layout for multiple images. The component also responds as the viewport changes. Developers can configure a loader function to build image URLs for another optimization service, using values such as source, width, and quality.

Takeaways

  • Import local images to have Next.js infer dimensions and reduce layout shift.
  • Allowlist remote image hosts and paths in the Next.js config.
  • Pair `fill` with a positioned parent, a defined size, and an appropriate `sizes` value.
  • Use `object-fit: cover` and CSS Grid for flexible image galleries.
  • Configure a loader when you want image URLs generated for another optimization service.

Mentioned in this talk

Search inside this talk

What was claimed 8

Related talks

Using Images in Next.js · WhoBuilt