Theo's Typesafe CultTTC
Theo's Typesafe Cult2y ago
13 replies
kal

next 14 Showing image fallback on public folder image 404

I am using next 14, and storing some images in my app's
public
folder. These images are then requested by <img> elements in some of my client components.

If the requested resource does not exist, I would like to show a 'default image' which is effectively a file that is guarnateed to exist in the public folder.

To try and do this I have written a simple client component that wraps the img element.

"use client";

import { useEffect, useState } from "react";

type Props = React.ImgHTMLAttributes<HTMLImageElement> & {
  src: string;
  fallbackSrc?: string;
};

export default function ImageWithFallback({
  fallbackSrc,
  src,
  ...props
}: Props) {
  const [hasErrored, setHasErrored] = useState<boolean>(false);
  const [activeSrc, setActiveSrc] = useState<string>(src);

  useEffect(() => {
    console.log(hasErrored);
    if (hasErrored && fallbackSrc !== undefined) setActiveSrc(fallbackSrc);
  }, [hasErrored]);

  return (
    <img
      {...props}
      src={activeSrc}
      onError={(e) => {
        setHasErrored(true);
      }}
    />
  );
}


However, the 'onError' callback is never fired. I believe this is because althought Next is in fact responding with 404 it is also sending a response body. (the default not-found HTML).

I have attached images showing that when the image content is requested, as stated the server responds with a 404, however also sends content in the response body. I wonder if because there is techincally a 'response' the image element is trying to display the response body content (the HTML) as the content of the image, and thus the onError callback does not fire.

Can anyone think of an alternative approach / fix to present a different image on image load fails from the public folder. Perhaps a different callback attribute on the img element could be leveraged and we could somehow check if the response was a 200? (or atleast not 404) ?
image.png
image.png
Was this page helpful?