Optimizing Images

The next/image component automatically resizes, lazy-loads, and serves modern image formats.

Syntax<Image src={img} alt="..." width={800} height={400} />

Use next/image instead of a plain <img> to get automatic optimization: correctly sized images, lazy loading, modern formats like WebP, and reserved space to prevent layout shift.

Key props

  • src, alt — as usual.
  • width and height — required for local/remote images to reserve space (or use fill).
  • priority — eagerly load an above-the-fold hero image.

Example

Example · typescript
import Image from 'next/image';
import hero from './hero.jpg';

export default function Banner() {
  return (
    <Image
      src={hero}
      alt="Mountain landscape"
      width={800}
      height={400}
      priority
    />
  );
}

When to use it

  • A product listing page uses next/image to serve WebP thumbnails at the right size for each viewport automatically.
  • A hero image is marked priority in next/image so Next.js preloads it for the best Largest Contentful Paint score.
  • A blog post renders user-uploaded images with next/image to lazy-load below-the-fold images without any extra code.

More examples

Basic next/image usage

next/image requires explicit width and height to reserve space and prevent layout shift during load.

Example · ts
import Image from 'next/image';

export default function Avatar() {
  return (
    <Image
      src="/avatar.jpg"
      alt="User avatar"
      width={80}
      height={80}
    />
  );
}

Priority hero image

priority tells Next.js to preload the image with a link rel=preload tag, improving LCP for above-the-fold images.

Example · ts
import Image from 'next/image';

export default function Hero() {
  return (
    <div style={{ position: 'relative', width: '100%', height: '400px' }}>
      <Image
        src="/hero.jpg"
        alt="Hero banner"
        fill
        priority
        style={{ objectFit: 'cover' }}
      />
    </div>
  );
}

Remote image with next.config

remotePatterns in next.config.ts whitelists external domains so next/image can optimise and proxy their images.

Example · ts
// next.config.ts
import type { NextConfig } from 'next';
export default {
  images: {
    remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
  },
} satisfies NextConfig;

// Usage:
// <Image src="https://images.unsplash.com/photo-xyz" alt="..." width={400} height={300} />

Discussion

  • Be the first to comment on this lesson.