How to Check Image Exists in Public Folder of Next JS

717 Views Asked by At

I have a TypeScript Next.js project that has thousands of images in the public folder. Is there any way I can check an existing image before using the <Image /> component in next/image?

I was able to do this using JavaScript only, but TypeScript is too complex. I also get an error returned from Next.js that says:

The requested resource is not a valid image for /cars/audi-4.jpg received text/html; charset=utf-8

ImageError: The requested resource is not a valid image.

How to check for existing /cars/audi-4.jpg? I would like to use a default image if it does not exist.

1

There are 1 best solutions below

0
avinashcodelabs On

src\app\page.js (Next.js 13 app)

Check the embedded comments for the flow

import Image from "next/image";

// Using HEAD method, just check the headers for status code
const isImageFound = async (imageName) => {
  return await fetch(`http://localhost:3000${imageName}`, {
    method: "HEAD",
  });
};

export default async function Home() {
  // default image name assignment
  let imageName = "/default.jpg";

  // this is the image we are looking for, not sure where you ar gonna pick this.
  let anyExistingImage = "/one.jpg";

  // Check the image is exists in public folder, if not take default image to render.
  const result = await isImageFound(anyExistingImage);
  if (result.status === 200) {
    imageName = anyExistingImage;
  }

  return <Image src={imageName} width={300} height={300} />;
}

Folder structure with Public folder and page.js for Next.js 13 app,

enter image description here

I hope this helps