Loading Images in NextJS: A Complete Guide to next/image

Cover Image for Loading Images in NextJS: A Complete Guide to next/image
toofancoder
toofancoder

Loading Images in NextJS Using next/image

The next/image component is NextJS's solution for automatic image optimization. Let's explore how to use it across different NextJS versions and handle common scenarios.

NextJS Versions and Implementation

NextJS 13+ (App Router)

import Image from 'next/image'

function MyComponent() {
  return (
    <Image
      src="/example.jpg"
      alt="Example Image"
      width={500}
      height={300}
      priority={false}
    />
  )
}

NextJS 12 and earlier (Pages Router)

import Image from 'next/image'

function MyComponent() {
  return (
    <Image
      src="/example.jpg"
      alt="Example Image"
      width={500}
      height={300}
      layout="responsive"  // Deprecated in NextJS 13+
    />
  )
}

Configuration in next.config.js

NextJS 13+

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    domains: ['example.com'], // Allow external domains
    remotePatterns: [
      {
        protocol: 'https',
        hostname: '**.example.com',
        port: '',
        pathname: '/images/**',
      },
    ],
  },
}

module.exports = nextConfig

NextJS 12 and earlier

module.exports = {
  images: {
    domains: ['example.com'],
    loader: 'default',
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },
}

Common Errors and Solutions

1. Invalid src prop

Error: Invalid src prop (https://example.com/image.jpg) on `next/image`, hostname "example.com" is not configured under images in your `next.config.js`

Solution: Add the domain to your next.config.js:

images: {
  domains: ['example.com']
}

2. Missing Required Props

Error: Image with src "/example.jpg" must use "width" and "height" properties or "fill" property.

Solution: Always provide width and height, or use fill:

// Option 1: With dimensions
<Image src="/example.jpg" width={500} height={300} alt="Example" />

// Option 2: With fill
<div style={{ position: 'relative', width: '100%', height: '300px' }}>
  <Image src="/example.jpg" fill alt="Example" style={{ objectFit: 'cover' }} />
</div>

3. Blurry Placeholder Issues

For better loading experience, you can use blur placeholder:

<Image
  src="/example.jpg"
  alt="Example"
  width={500}
  height={300}
  placeholder="blur"
  blurData="data:image/jpeg;base64,/9j..." // Base64 encoded small image
/>

Best Practices

  1. Always use alt tags for accessibility
  2. Use priority prop for LCP (Largest Contentful Paint) images
  3. Implement responsive images using appropriate sizes prop
  4. Consider using quality prop (default is 75)
<Image
  src="/example.jpg"
  alt="Example"
  width={500}
  height={300}
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  quality={85}
/>

Loading Remote Images

When loading images from external sources, ensure you configure the domains or patterns in your next.config.js. For dynamic URLs, you might need to use remotePatterns:

images: {
  remotePatterns: [
    {
      protocol: 'https',
      hostname: '**.amazonaws.com',
    },
  ],
}

Remember that the Image component helps with:

  • Automatic optimization
  • Immediate rendering with correct dimensions
  • Preventing Cumulative Layout Shift (CLS)
  • Lazy loading by default
  • Serving modern image formats like WebP when supported

For more advanced use cases and detailed documentation, refer to the official NextJS Image documentation.