Got an error Invalid src prop ('here is a link') on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`

Viewed 33207

I am using the Image component from Next.js (it's a new feature of Next.js). I've tried to give the source URL:

{`${API}/user/photo/${blog.postedBy.username}`}

But it shows me this error. I also make changes in my next.config.js as

module.exports = {
    images: {
      domains: ['localhost'],
    },
  }

but nothing works for me. Please help if you know anything about this.

7 Answers
const src = `${API}/user/photo/${blog.postedBy.username}`;
    
<Image loader={() => src} src={src} width={500} height={500}/>

Here, loader is a function that generates the URLs for your image. It appends a root domain to your provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.

Yes, I finally got the answer. Make loader function to load it from the destination of the image.

const myLoader=({src})=>{
  return `${API}/user/photo/${blog.postedBy.username}`;
}

Use this loader function the loader attribute of an Image tag.

<Image loader={myLoader} src={`${API}/user/photo/${blog.postedBy.username}`} width={500}
    height={500}/>

This works for me perfectly

Edit next.config.js :

module.exports = {
  reactStrictMode: true,
  images: {
    domains: ['example.com'],
  },
}

I had the same issue, You need to restart your dev server, you need to do that each time you make changes on your next.config.js file.

The API string should include the port. e.g. localhost:3001

First of all add and restart the dev server.

domains: ['localhost']

And be sure to return the image link with http(s) protocole

image link with localhost:port/... is wrong , return as http://localhost/... ( or with https )

Inside next.config.js file.

Add Image src domain name:

const nextConfig = {
  reactStrictMode: true,
  images : {
    domains : ['sangw.in', 'localhost', 'picsum.photos'] // <== Domain name
  }
}

module.exports = nextConfig

Adding 'localhost' in the domains array will fix the issue,

Unfortunately nextJS didn't refresh the server automatically after configuration file(next.config.js) change.

You have to restart the server manually to reflect the changes.

You can also try by set reactStrictMode value reactStrictMode: true,

here is the full export object

module.exports = {
    reactStrictMode: true,
    images: {
        domains: [
            "localhost",
            process.env.WORDPRESS_API_URL.match(/(http(?:s)?:\/\/)(.*)/)[2], // Valid WP Image domain.
            "2.gravatar.com",
            "0.gravatar.com",
            "secure.gravatar.com",
        ],
    },
};
Related