0
0
NextjsDebug / FixBeginner · 4 min read

How to Handle Remote Images in Next.js Correctly

In Next.js, to handle remote images with the next/image component, you must add the remote image domains to the next.config.js file under the images.domains array. This allows Next.js to optimize and serve images from those external sources safely.
🔍

Why This Happens

Next.js blocks remote images by default for security and performance reasons. If you try to use the next/image component with a remote URL without configuring allowed domains, you get an error.

javascript
import Image from 'next/image';

export default function Profile() {
  return (
    <Image
      src="https://example.com/photo.jpg"
      alt="Profile photo"
      width={200}
      height={200}
    />
  );
}
Output
Error: Invalid src prop (https://example.com/photo.jpg) on `next/image`, hostname "example.com" is not configured under images.domains in your `next.config.js`
🔧

The Fix

To fix this, add the remote image domain to the images.domains array in your next.config.js. This tells Next.js to allow and optimize images from that domain.

javascript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    domains: ['example.com'],
  },
};

module.exports = nextConfig;

// Usage in component
import Image from 'next/image';

export default function Profile() {
  return (
    <Image
      src="https://example.com/photo.jpg"
      alt="Profile photo"
      width={200}
      height={200}
    />
  );
}
Output
<img src="/_next/image?url=https%3A%2F%2Fexample.com%2Fphoto.jpg&w=200&q=75" alt="Profile photo" width="200" height="200">
🛡️

Prevention

Always list all external image domains you plan to use in next.config.js before using them with next/image. This prevents runtime errors and ensures images are optimized.

Use linting or code reviews to catch missing domain configurations early. Also, prefer using the next/image component over <img> for better performance and automatic optimization.

⚠️

Related Errors

Other common errors include:

  • Static import required: When using local images, you must import them instead of using string URLs.
  • Missing width or height: The next/image component requires explicit width and height props or layout="fill" to prevent layout shifts.

Key Takeaways

Add remote image domains to next.config.js under images.domains to allow external images.
Use the next/image component for optimized image loading and better performance.
Always specify width and height props on next/image to avoid layout shifts.
Check your configuration before using new remote image URLs to prevent errors.
Use linting and code reviews to catch missing domain entries early.