next js image optimization

Intermediate

Next.js Image Optimization: Intermediate Study Guide

Core Concepts

1. The next/image Component

  • Purpose: Automatically optimizes images (resizing, converting to modern formats, lazy-loading) for better performance.
  • Key Features:
    • Automatic Optimization: Images are served from Next.js's built-in optimizer via next/image.
    • Modern Formats: Converts images to WEBP or AVIF when the browser supports them.
    • Responsive Images: Generates multiple sizes for different screen resolutions.
    • Lazy Loading: Images load only when they enter the viewport (except when marked as priority).
    • Inline Loading: Critical images can be inlined directly into CSS/JS for faster initial load.

2. Static vs. Dynamic Imports

  • Static Imports (at the top of the file):

    import myImage from './path/to/image.jpg';
    
    • Optimization: Next.js knows the image path at build time and optimizes it.
    • Best for: Images that are known at build time (e.g., logos, icons).
  • Dynamic Imports (using public folder):

    <Image src="/images/dynamic.jpg" alt="Dynamic" width={500} height={300} />
    
    • Optimization: Images are optimized at request time via the Next.js optimizer.

3. Key Props

PropDescription
srcSource of the image. Must be statically analyzable or from the public folder.
altRequired. Describes the image for accessibility and SEO.
widthRequired. Width of the image in pixels.
heightRequired. Height of the image in pixels.
sizesSpecifies responsive sizes e.g., "(max-width: 768px) 100vw, 50vw"
priorityForces the image to load immediately (adds fetchpriority="high").
placeholder'blur' or 'empty' for loading UX. 'blur' uses a blurred low-res version.
qualitySets image quality (1–100). Default is 75.

4. Remote Images

  • Default: Next.js only optimizes images from the same domain.
  • Configuration (next.config.js):
    module.exports = {
      images: {
        domains: ['example.com', 'cdn.myimages.com'],
      },
    };
    

5. Custom Loaders

  • Use Case: Offload optimization to a CDN (e.g., Cloudinary, Imgix).
  • Example:
    // next.config.js
    module.exports = {
      images: {
        loaders: [
          {
            name: 'custom-loader',
            path: 'https://res.cloudinary.com/my-account/image/upload',
          },
        ],
      },
    };
    
    // In component
    <Image
      src="my-image.jpg"
      loader={({ src }) => `/custom-loader?url=${src}`}
      alt="Cloudinary Image"
      width={500}
      height={300}
    />
    

Common Interview Questions & Ideal Answers

Q1. What are the main advantages of using next/image over a standard <img> tag?

Answer:

The next/image component provides automatic optimization (resizing, format conversion, compression) and ensures correct loading behavior (lazy-loading, priority hints). It also enforces accessibility best practices by requiring alt text and prevents layout shift by requiring explicit width/height. Additionally, it integrates seamlessly with Next.js's static optimization and supports responsive images via the sizes prop.


Q2. Explain how next/image handles responsive images.

Answer:

When you provide the sizes prop, Next.js generates multiple image sizes (based on the device pixel ratio) and includes a srcset attribute. The browser then selects the optimal image based on viewport size and device capabilities. For example:

<Image
  src="/image.jpg"
  alt="Responsive"
  width={500}
  height={300}
  sizes="(max-width: 768px) 100vw, 50vw"
/>

This ensures the correct image size is loaded for mobile vs. desktop, reducing bandwidth usage.


Q3. How do you handle images hosted on external domains?

Answer:

By default, Next.js only optimizes images from the same origin. To enable external images:

  1. Add the domain to domains in next.config.js:
    // next.config.js
    module.exports = {
      images: {
        domains: ['example.com'],
      },
    };
    
  2. Ensure CORS headers are correctly configured on the external server.
  3. Alternatively, use a custom loader for CDNs (e.g., Cloudinary).

Q4. What is the difference between placeholder="blur" and placeholder="empty"?

Answer:

  • "blur": Next.js generates a low-resolution blurred placeholder (a.k.a. "blur-up") from the image’s dominant colors. This provides visual context while the full image loads.
  • "empty": Shows a blank (transparent) area until the image loads. Useful for solid-background images where a blur might not be helpful.

Q5. When should you use the priority prop?

Answer:

Use priority for above-the-fold images that are visible during the initial load (e.g., hero banners, logos). It:

  • Prefetches the image.
  • Adds fetchpriority="high".
  • Disables lazy-loading.
  • Ensures the image is inlined if possible.

Real-World Examples

Example 1: Basic Optimized Image

import heroImage from './hero.jpg';

export default function Home() {
  return (
    <div>
      <Image
        src={heroImage}
        alt="Hero Section"
        width={1200}  // Actual width of the image
        height={800}  // Actual height of the image
        priority      // Load immediately
        placeholder="blur"
      />
    </div>
  );
}

Example 2: Remote Image with Configuration

// next.config.js
module.exports = {
  images: {
    domains: [' resaleapi.com'],
  },
};
// Component
<Image
  src="https://resaleapi.com/images/product.jpg"
  alt="Product"
  width={600}
  height={400}
  sizes="(max-width: 600px) 100vw, 600px"
/>

Study Tips

  1. Hands-On Practice:

    • Build a sample Next.js app and experiment with next/image in both Pages Router and App Router.
    • Compare Lighthouse scores before/after using next/image.
  2. Configuration Deep Dive:

    • Explore next.config.js options: deviceSizes, imageSizes, domains, and custom loaders.
    • Test with large images to see optimization in action.
  3. Performance Metrics:

    • Use Chrome DevTools Network tab to inspect loaded image sizes and formats.
    • Analyze Core Web Vitals (CLS, LCP) impact.
  4. Edge Cases:

    • How does next/image handle SVGs? (Requires next/image v12+ and width/height.)
    • What happens if width/height are mismatched? (Next.js will attempt to infer but may cause layout shift.)
  5. Stay Updated:


💡 Need clarification or want to simulate a mock interview? Ask me any question!

Ready for a new challenge?

Start a new session to explore different topics or increase the difficulty level.

Start New Session
next js image optimization Preparation Guide | Interview Preparation