imagenext.jsloading

Next.js throws error error when trying to load image from API


So I have an API (Springboot) that stores images as files. I want to retrieve these images and display them in NextJS, but no matter what there's an error. In Postman, everything works fine, so it's not an API problem.

First I tried simply using the url as the src:

<Image src={'localhost:6969/assets/download/1'} alt="image" width={100} height={100} />

This gave a big error that broke down the whole site (I forgot what was the error). After some digging, I found out I had to put a loader. So I did.

const loadImage = ({src}) => {
    return 'localhost:6969/assets/download/1?widht=100&height=100';
}
...
<Image loader={loadImage} src={'localhost:6969/assets/download/1'} alt="image" width={100} height={100} />

Then my image tag was being loaded but with no image, and it threw a warning that the image is not optimized followed by an error:

The image is not loading

Image with src "localhost:6969/assets/download/1" has a "loader" property that does not implement width. Please implement it or use the "unoptimized" property instead. (Warn)

GET localhost:6969/assets/download/1 net::ERR_UNKNOWN_URL_SCHEME

So I put the unoptimized tag on the image and modified the url, even if my API doesn't use these options in the url:

const loadImage = ({src}) => {
    return 'localhost:6969/assets/download/1?width=100&height=100';
}
...
<Image loader={loadImage} src={'localhost:6969/assets/download/1?width=100&height=100'} alt="image" width={100} height={100} unoptimized />

This removed the warning, but still threw the same error and the image is still not loading. I looked at the network tab in the console, and I saw that the request was failing. On my API, I saw no call for the image.

I read that images can only be loaded from the public folder. Is there a way to download the images from my Springboot API to the public folder or something similar ? Am I missing something ?

So now I'm left here, with a bug I don't understand and a project in fast need of completion. Any help would be very much appreciated.


Solution

  • I figured it out. The url just needs to have http:// at the start.

    Instead of localhost:6969/assets/download/1?width=100&height=100, it should be http://localhost:6969/assets/download/1?width=100&height=100. The url can even have no options, so in the end it can just be http://localhost:6969/assets/download/1, and the <Image /> tag can have no loader but has to keep the unoptimized option. So the end result is an elegant Image tag that looks like this:

    <Image src={'http://localhost:6969/assets/download/1'} alt="image" width={100} height={100} unoptimized />

    Hope this helps someone out there.