tezvyn:

Next.js `next/image`: Stop Shipping Giant Images

AI-drafted, machine-checkedSource: nextjs.orgbeginner

The `next/image` component is an automated image pipeline, not just an `<img>` tag. It resizes, optimizes, and serves modern formats like WebP, improving load times. The footgun is forgetting to provide `width` and `height`, causing layout shifts.

WHY IT EXISTS: Unoptimized images are a primary cause of slow websites. Developers using a standard <img> tag must manually resize images for different devices, convert them to modern formats, and implement lazy loading. This is tedious and often forgotten, leading to poor user experience and bad SEO scores from Core Web Vitals.

THE MENTAL MODEL: The next/image component is an automated image pipeline, not just a wrapper for an <img> tag. It intercepts your image and serves a perfectly sized, optimized, and modern-formatted version based on the user's device and browser. You provide one high-quality source image, and Next.js handles the rest.

HOW IT WORKS: When you use the <Image> component, Next.js performs several optimizations. First, it requires width and height attributes to prevent Cumulative Layout Shift (CLS) by reserving the correct space in the layout before the image loads. Second, it automatically generates smaller versions of your image for different viewports. Third, it serves the image in a modern format like WebP or AVIF if the browser supports it, falling back to JPEG or PNG otherwise. Finally, images are lazy-loaded by default, meaning they don't load until they are about to enter the viewport, saving initial bandwidth.

WHEN TO USE IT: Use next/image for almost any image in a Next.js application, whether it's a local static asset or a remote image from a CDN. It's the default and recommended way to display images to get significant performance benefits with minimal effort.

WHEN NOT TO USE IT: Avoid it for purely decorative images that are better handled as CSS backgrounds. If you need to perform complex client-side manipulations that the component might interfere with, a standard <img> tag could be a last resort, but you will lose all optimization benefits. It's also cumbersome for images from a vast, unpredictable set of user-provided domains, as each one would need to be whitelisted.

ONE CANONICAL EXAMPLE: To use a local image, you import it and pass it to the src prop, like <Image src={profilePic} alt="Author" width={500} height={500} />. For a remote image, you provide the URL string, like <Image src="https://..." alt="Remote photo" width={1200} height={800} />. A common footgun is forgetting that for remote images, you must add the hostname (e.g., 'images.unsplash.com') to your next.config.js file for security.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.