4

I'm using dynamic images. Everything works fine on localhost, but as soon as I deploy my next.js-app on vercel, only the fallback image is shown (I get a 404 error for the default image).

Btw, when I hard-code an image, instead of using the dynamic path, everything works. So I think the issue is somewhere in the dynamic path (?).

Here is the relevant code:

function isImageValid(src) {
  let promise = new Promise((resolve) => {
    let img = document.createElement("img");
    img.onerror = () => resolve(false);
    img.onload = () => resolve(true);
    img.src = src;
  });

  return promise;
}

function Img({ src, fallbackSrc, ...rest }) {
  const imgEl = React.useRef(null);
  React.useEffect(() => {
    isImageValid(src).then((isValid) => {
      if (!isValid) {
        imgEl.current.src = fallbackSrc;
      }
    });
  }, [src]);

  return <img {...rest} ref={imgEl} src={src} />;
} 
 
const ItemImage = ({ company, name }) => {
  return (
    <Img
      alt="some image"
      src={`/assets/items/${company
        .toLowerCase()}-${
        name
          .toLowerCase()}.png`}
      fallbackSrc="/assets/fallback-img.jpg"
    />
  );
};

Generally, I'm using next-images. I'm not using next/images, because the images vary in their size and I didn't find a good solution for that by now. (But even if I'm trying to use next/images despite the bad formatting, I get the same error.)

Could someone tell me what I'm missing or doing wrong? Thanks a lot!!

Ewax_Du
  • 325
  • 1
  • 8
  • 22
  • Please check https://stackoverflow.com/help/minimal-reproducible-example – paulogdm May 18 '21 at 11:46
  • Do you get the same issue if you run a prod build locally? Are the URLs for the images correct in production? – juliomalves May 18 '21 at 11:56
  • 3
    @juliomalves: Thanks a lot! You helped me to find the issue: the URLs of the images were incorrect (all lowercase). This wasn't a problem in development, but in production.. – Ewax_Du May 19 '21 at 17:48

1 Answers1

2

I got help from comments. The problem was with the url of the image.

the path to image is case-sensitive. Make sure it matches everything.

To help debug, run production build locally.

My package.json is

  "scripts": {
    "dev": "next lint & NODE_OPTIONS='--inspect' next dev",
    "build": "next build",
    "start": "next start",
    "prod": "next build && next start"
  },

run npm run prod to see the production build locally.

Rohit
  • 6,365
  • 14
  • 59
  • 90