Next.js Image component with external dynamic source

Viewed 3079

I was working on my Next.js project and while running it locally html img tag worked okay. While building, I got a warning, to change it to Image component from Next.js

So I did, but now I get a warning:

Error: Invalid src prop (https://image.ceneostatic.pl/data/products/10813131/i-dixit.jpg) on next/image, hostname "image.ceneostatic.pl" is not configured under images in your next.config.js See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

I read in the documentation that solution is to add a domain to next.config.js. But 2 problems occurs to me here:

  1. Even if I specify a domain like this, it doesn't work

    module.exports = { images: { domains: ['image.ceneostatic.pl'], }, };

  2. I have my project connected to MongoDB, where are stored links to the images. What's more, I want an user to pass a link, while creating a new entry. So I don't want to have hard-coded domains, as I don't know which img an user will use.

Is there a way to omit domains list or a walk-around to use tag?

Thanks!

1 Answers

You can use something called next Loader via the following code:

import Image from 'next/image'


const myLoader = ({ src, width, quality }) => {
  return `https://image.ceneostatic.pl/data/products/{src}/i-dixit.jpg`
}
var photoID = 10813131

const MyImage = (props) => {
  return (
    <Image
      loader={myLoader}
      src=photoID
      width={500}
      height={500}
    />
  )
}

Your next.config.js:

module.exports = {
  images: {
    loader: 'imgix',
    path: 'https://image.ceneostatic.pl',
  },
}

All documentation is linked here.

Related