Home > front end >  Next JS Image Component works for static image files, but dynamic urls fail to load images
Next JS Image Component works for static image files, but dynamic urls fail to load images

Time:01-02

I am using NextJS <Image /> component. I am using both local image sources and sources from external API. Everything works in my local development environment, but as soon as I host it on the server to production, dynamic images from API are not showing up.

<Image
  src="house.jpg"   // loaded from local and works fine
  alt="Picture of my house."
  width={250}
  height={250}
/> 

The code below works in dev environment, but not in production server.

const renderHouses = (apiHouses) => (
   apiHouses.map(house => (
      <div key={house.id}>
         <Image
           src={house.img}   // not working (loading) on production server
           alt={`Picture of ${house.name}`}
           width={250}
           height={250}
         /> 
      </div>
   ))
)

CodePudding user response:

Yep, it will work for your localhost, but external images would not be loaded in production env if you don't specify the domain name in your next.config.js file.

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

You can find more info here.

  • Related