typescriptbeginner

Next.js Image Optimization Patterns

Advanced next/image usage with responsive sizes, blur placeholders, and custom loaders.

typescript
import Image from 'next/image';

// Basic optimized image
export function HeroImage() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero banner"
      width={1200}
      height={600}
      priority  // Preload for LCP
      className="rounded-lg"
    />
  );
}

// Responsive image with sizes
export function ResponsiveImage() {
  return (
    <Image
      src="/product.jpg"
      alt="Product"
      width={800}
      height={600}
      sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
      className="w-full h-auto"
    />
  );
}

// Fill container (replaces layout='fill')
export function BackgroundImage() {
  return (
    <div className="relative aspect-video">
      <Image
        src="/bg.jpg"
        alt="Background"
        fill
        className="object-cover rounded-xl"
        sizes="100vw"
      />
    </div>
  );
}

// Blur placeholder
export function BlurImage() {
  return (
    <Image
      src="/photo.jpg"
      alt="Photo"
      width={640}
      height={480}
      placeholder="blur"
      blurDataURL="data:image/jpeg;base64,/9j/4AAQ..." // tiny base64
    />
  );
}

// Custom loader for external CDN
const cloudinaryLoader = ({
  src, width, quality,
}: { src: string; width: number; quality?: number }) => {
  return `https://res.cloudinary.com/demo/image/upload/w_${width},q_${quality || 75}/${src}`;
};

export function CDNImage() {
  return (
    <Image
      loader={cloudinaryLoader}
      src="sample.jpg"
      alt="CDN image"
      width={500}
      height={300}
    />
  );
}

Use Cases

  • Optimizing Core Web Vitals with proper image loading
  • Responsive images for mobile and desktop
  • Loading images from external CDNs

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.