Ewax_Du
Ewax_Du

Reputation: 465

Next.js + Vercel: Dynamic images displaying locally, but not in production

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!!

Upvotes: 5

Views: 5558

Answers (1)

Rohit
Rohit

Reputation: 6613

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.

Upvotes: 2

Related Questions