[SOLVED] Error: Invalid src prop on next/image
When you try to access an image in your NextJS project from a domain name which is not configured under images in your NextJS config then you will get the following error:
Error: Invalid src prop (https://www.studytonight.com/logo/study-logo.svg) on `next/image`, hostname "studytonight.com" is not configured under images in your `next.config.js`
In the error above, the domain name studytonight.com is not configured, for you it can be some other domain name.
Why we get this error?
In NextJS, if you want to use images from any other domain like Amazon s3, or a CDN, then you must add the domain name into next.config.js file, so that the NextJS app knows that the domain name is trusted.
If you don't specify the domain names to the NextJS application, then it will show the following error.
How to Fix it?
Fix for this issues is very easy. All you have to do is list the domain name or domain names (if multiple) using the images.remotePatterns
config in the next.config.js file.
You can find the next.config.js or next.config.mjs file in the root of your NextJS project.
You can add the images.remotePatterns
config like this,
const nextConfig = {
images: {
remotePatterns: [{
protocol: 'https',
hostname: 'example.com'
port: '',
pathname: '/images/**'
}],
}
};
Just like this, you can add multiple domain names in the remotePatterns
array.
If you are using Next version 12.3.0 or older, then you can do it like this:
module.exports = {
images: {
domains: ['assets.example.com'],
},
}
And this will fix your error.
End Note
This is a way to enforce config based security in NextJS application where you cannot use an image without specifying that the image is coming from a known domain name.
And the configuration is central to the NextJS project with all the other project related configuration like redirects, rewrites, etc.