This error means the hostname you're trying to use for image loading in Next.js is not configured in the next.config.js
file.
When using Next.js's Image
component from the next/image
package, it is necessary to specify any external domains you want to load images from in your next.config.js
file.
The reason is explained below.
Here's an example of how you can add hostnames to your Next.js configuration:
module.exports = {
images: {
domains: ['example.com', 'learnbestcoding.com'],
},
}
In the above configuration, example.com
and learnbestcoding.com
are the hostnames from which I plan to load images. You need to replace them with the domains you use in your project.
Then I can load the image like the one below:
<Image width={40} height={40} src="learnbestcoding.com/duck_dance.webp" alt="duck"/>
Why do I have to configure the domain in next.config.js?
When using the next/image
component in Next.js, I need to specify external domains in the next.config.js
file for a couple of reasons:
- Security: By specifying a list of allowed domains, you prevent potential security risks of loading images from random URLs. That could include, for example, loading an image that carries malicious code or from an insecure source.
- Optimization: The
next/image
component provides several benefits, such as automatic resizing, optimizing images for different devices, and lazy loading. When you specify an image URL, Next.js will first fetch the image to its server, then perform these optimizations before sending it to the client. That is why Next.js needs to know the domains of the images in advance - so it can safely fetch and optimize them.