---
title: "Image Optimization in Next.js with next/image"
url: https://www.khanwaseem.com/blog/nextjs-tutorial/image-optimization-in-next-js
author: "khan Waseem"
published: 2026-11-24
updated: 2026-11-24
topics: ["Nextjs Tutorial", "course"]
description: "Make your pages load faster with the next/image component: automatic resizing and modern formats, lazy loading, blur placeholders, the sizes prop, fill mode, remote images with remotePatterns and preloading the main…"
---

# Image Optimization in Next.js with next/image

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Using the Image Component](#using-the-image-component)[1. Local Images:](#1-local-images)
- [2. Remote Images:](#2-remote-images)

- [What Next.js Does Behind the Scenes](#what-nextjs-does-behind-the-scenes)
- [The sizes Prop](#the-sizes-prop)
- [Filling a Container with fill](#filling-a-container-with-fill)
- [Preloading the Main Image](#preloading-the-main-image)
- [Other Useful Props and Settings](#other-useful-props-and-settings)
- [Common Mistakes](#common-mistakes)[1. Forgetting width and height:](#1-forgetting-width-and-height)
- [2. Missing sizes on responsive images:](#2-missing-sizes-on-responsive-images)
- [3. Lazy-loading the hero image:](#3-lazy-loading-the-hero-image)
- [4. Using fill without a positioned parent:](#4-using-fill-without-a-positioned-parent)

- [Conclusion:](#conclusion)

## Introduction:

Images are usually the heaviest part of a web page. A single photo straight from a phone can be 4 MB, while the visitor’s screen only needs a 100 KB version of it. Large images make pages slow, use up mobile data, and hurt your Google ranking through the **Core Web Vitals** scores, especially **LCP** (Largest Contentful Paint) and **CLS** (Cumulative Layout Shift).

Next.js solves most of this with one component: **`next/image`**. It is a replacement for the HTML `<img>` tag that automatically:

- **Resizes** each image to the size the visitor’s screen actually needs.

- Converts it to a **modern format** such as WebP or AVIF, which are much smaller than JPEG and PNG.

- **Lazy loads** images, so images further down the page are only downloaded when the visitor scrolls near them.

- **Prevents layout shift** by reserving the right amount of space before the image loads.

In the [previous lesson](https://blog.khanwaseem.com/deploying-next-js-to-vercel/) we deployed our app to Vercel, where all of this works without any setup. Now let’s learn how to use it.

## Using the Image Component

Import `Image` from `next/image` and use it like an `<img>` tag. The `alt` text is required: it describes the image for screen readers and search engines.

### 1. Local Images:

The easiest way is to **import** an image file from your project. Next.js reads the file at build time, so it already knows the width and height, and it can even create a tiny blurred preview of it.

```javascript
import Image from "next/image";
import hero from "../public/images/hero.jpg";

export default function Home() {
  return <Image src={hero} alt="Mountains at sunrise" placeholder="blur" preload />;
}Code language: JavaScript (javascript)
```

`placeholder="blur"` shows a blurred version of the image while the real one loads, which looks much nicer than an empty box. We will look at `preload` a little later.

You can also refer to a file in the `public` folder by its path, as a string. In that case Next.js cannot read the file, so you must give the `width` and `height` yourself:

```xml
<Image src="/images/hero.jpg" alt="Mountains at sunrise" width={1200} height={800} />Code language: HTML, XML (xml)
```

The `width` and `height` are not the size the image is displayed at (CSS controls that). They tell Next.js the image’s **aspect ratio**, so the browser can reserve the right space and nothing on the page jumps when the image appears.

### 2. Remote Images:

For images hosted elsewhere, such as a CMS, a storage bucket or a CDN, use the full URL and give `width` and `height`:

```xml
<Image
  src="https://blogkhanwaseem.s3.amazonaws.com/uploads/2026/11/23101504/cover-deploying-next-js-to-vercel-2602.png"
  alt="Deploying a Next.js App to Vercel"
  width={1200}
  height={630}
  sizes="(max-width: 768px) 100vw, 768px"
/>Code language: HTML, XML (xml)
```

For safety, Next.js will **not** optimize images from any website on the internet. Otherwise anyone could use your server to resize their images. You list the allowed sources in `next.config.js` with `remotePatterns`:

```javascript
// next.config.js
/** @type {import('next').NextConfig} */
module.exports = {
  images: {
    remotePatterns: [
      new URL("https://images.unsplash.com/**"),
      {
        protocol: "https",
        hostname: "blogkhanwaseem.s3.amazonaws.com",
        pathname: "/uploads/**",
      },
    ],
  },
};Code language: JavaScript (javascript)
```

If you forget this, the page shows an error in development telling you that the hostname is not configured. In production, a request for an image from a host that isn’t listed is refused with a `400 Bad Request` error. Restart the dev server after changing `next.config.js`. (Older tutorials use `images.domains`; it is deprecated, so use `remotePatterns`.)

## What Next.js Does Behind the Scenes

Let’s look at the HTML Next.js produces for the remote image above (shortened):

```xml
<img alt="Deploying a Next.js App to Vercel" loading="lazy" width="1200" height="630"
  decoding="async" sizes="(max-width: 768px) 100vw, 768px"
  srcSet="/_next/image?url=https%3A%2F%2Fblogkhanwaseem...png&w=640&q=75 640w,
          /_next/image?url=https%3A%2F%2Fblogkhanwaseem...png&w=750&q=75 750w,
          /_next/image?url=https%3A%2F%2Fblogkhanwaseem...png&w=828&q=75 828w,
          ...
          /_next/image?url=https%3A%2F%2Fblogkhanwaseem...png&w=3840&q=75 3840w"
  src="/_next/image?url=https%3A%2F%2Fblogkhanwaseem...png&w=3840&q=75"/>Code language: HTML, XML (xml)
```

A few important things are happening here:

- **`loading="lazy"`**: the browser waits to download the image until it is about to scroll into view.

- **`srcSet`**: a list of the same image at different widths. The browser picks the smallest one that is sharp enough for the visitor’s screen. A phone might download the 640-pixel version, while a large monitor gets the 1920-pixel one.

- **`/_next/image?url=...&w=640&q=75`**: every image goes through Next.js’s **image optimizer**. It downloads the original once, resizes it to the requested width, compresses it with quality 75, converts it to WebP (or AVIF if you enable it), and caches the result.

- **`width` and `height`**: they reserve the space, so there is no layout shift.

When we asked the optimizer for a 640-pixel version of a 60 KB, 2400×1600 JPEG, it sent back an AVIF image of only **335 bytes** (a plain grey test image, so real photos will be bigger, but the savings are just as dramatic).

## The sizes Prop

The browser chooses from the `srcSet` based on how wide the image will be **displayed**, but it has to decide before the CSS has loaded. The `sizes` prop tells it in advance:

```javascript
sizes="(max-width: 768px) 100vw, 768px"Code language: JavaScript (javascript)
```

This reads: “On screens up to 768 pixels wide, the image fills the whole viewport width (`100vw`). On larger screens, it is 768 pixels wide.” Without `sizes`, Next.js assumes the image is displayed at its full `width`, which is fine for fixed-size images but wastes bandwidth for images that shrink on mobile. A good rule: **always add `sizes` when the image’s displayed width changes with the screen size.**

Some common examples:

- Full-width banner: `sizes="100vw"`

- Two columns on desktop, one on mobile: `sizes="(max-width: 768px) 100vw, 50vw"`

- Three-column card grid: `sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"`

## Filling a Container with fill

Sometimes you don’t know the image’s size, or you want it to cover a box of a fixed shape, such as a card thumbnail or a hero banner. Use the `fill` prop instead of `width` and `height`. The image then stretches to fill its **parent**, which must have `position: relative` (or `absolute`/`fixed`) and a size.

```xml
<div style={{ position: "relative", width: "100%", aspectRatio: "16 / 9" }}>
  <Image
    src="/images/hero.jpg"
    alt="Banner"
    fill
    sizes="100vw"
    style={{ objectFit: "cover" }}
  />
</div>Code language: HTML, XML (xml)
```

`objectFit: "cover"` crops the image to fill the box without stretching it. Use `"contain"` if the whole image must stay visible, for example a product photo or a logo.

## Preloading the Main Image

Lazy loading is great for images further down the page, but it is a mistake for the **largest image at the top**, such as a hero banner or a product photo. That image is usually the page’s **LCP element**, and Google measures how fast it appears. You want it to start downloading immediately.

Add the `preload` prop to that one image:

```xml
<Image src={hero} alt="Mountains at sunrise" placeholder="blur" preload />Code language: HTML, XML (xml)
```

Next.js then turns off lazy loading for it and adds a preload hint to the page’s `<head>`, so the browser starts fetching it before it even reaches the `<img>` tag. Only use `preload` for one or two images that are visible as soon as the page opens. (In Next.js 15 and older this prop was called `priority`. It still works in Next.js 16 but is deprecated.)

## Other Useful Props and Settings

- **`quality`**: the compression quality from 1 to 100 (default 75). Since Next.js 16 only the qualities listed in `images.qualities` are allowed, and the default list is just `[75]`. To use `quality={90}`, add `qualities: [75, 90]` to the config; otherwise the optimizer rejects the request with a 400 error.

- **`formats`**: by default images are converted to WebP. AVIF is about 20% smaller but slower to encode. Enable both with `formats: ["image/avif", "image/webp"]` in `images`; the browser gets the best one it supports.

- **`unoptimized`**: serves the original file without changes. Useful for SVGs, small icons, and animated GIFs.

- **`placeholder="blur"` with remote images**: Next.js can’t create the blur preview for a remote image automatically, so you pass a small base64 image yourself with `blurDataURL`.

## Common Mistakes

### 1. Forgetting width and height:

A string `src` without `width` and `height` (and without `fill`) causes an error. Import the file instead, or give both values.

### 2. Missing sizes on responsive images:

Without `sizes`, an image that is displayed small on mobile may still be downloaded at desktop size. Add `sizes` whenever the image’s width changes with the screen.

### 3. Lazy-loading the hero image:

If your LCP score is poor, check that the main image at the top has `preload`. Don’t add it to every image, or nothing gets priority.

### 4. Using fill without a positioned parent:

With `fill`, the parent element needs `position: relative` and a height (or an `aspect-ratio`). Otherwise the image has no box to fill and will not show.

## Conclusion:

The `next/image` component gives you fast images with almost no effort: it resizes images for each screen, converts them to WebP or AVIF, lazy loads them, and prevents layout shift. Import local images to get the size and blur placeholder for free, allow remote hosts with `remotePatterns`, add `sizes` for responsive images, use `fill` to cover a box, and `preload` the main image at the top of the page. Your pages will load faster, use less data, and score better in Google’s Core Web Vitals.

In the next lesson we will look at the **App Router and Server Components**, the newer way to build Next.js applications.

### Related posts:

[CSS – Measurement Units](https://blog.khanwaseem.com/css-measurement-units/)
[HTML – Attributes](https://blog.khanwaseem.com/html-attributes/)
[CSS – Height & Width (Dimension)](https://blog.khanwaseem.com/css-height-width-dimension/)
[CSS – @ Rules](https://blog.khanwaseem.com/css-rules/)

Powered by [YARPP](https://yarpp.com).
