Next.js Performance

Image Optimization

Next/Image component, responsive images, lazy loading, and CDN optimization.

Advertisement

Image Optimization

Next/Image component, responsive images, lazy loading, and CDN optimization.

Overview

Next.js automatically optimizes images for performance.

Key Concepts

  • next/image — Optimized image component
  • Responsive Images — srcSet for different screen sizes
  • Lazy Loading — Load images on demand
  • Placeholder — Blur or empty placeholders
  • Remote Images — Optimize external images

Code Examples

import Image from 'next/image';

// Basic usage
function Avatar() {
  return (
    <Image
      src="/avatar.jpg"
      alt="User avatar"
      width={100}
      height={100}
      priority
    />
  );
}

// Responsive images
function HeroImage() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero image"
      fill
      sizes="(max-width: 768px) 100vw, 50vw"
      priority
      className="object-cover"
    />
  );
}

// Remote images
function ProductImage({ src, alt }) {
  return (
    <Image
      src={src}
      alt={alt}
      width={500}
      height={500}
      placeholder="blur"
      blurDataURL="/placeholder.png"
    />
  );
}

// Background image
function Hero() {
  return (
    <div className="relative h-96">
      <Image
        src="/hero-bg.jpg"
        alt="Hero background"
        fill
        className="object-cover"
        priority
      />
      <div className="relative z-10">
        <h1>Welcome</h1>
      </div>
    </div>
  );
}

Practice

Optimize a gallery page with responsive images and lazy loading.