How to check if image exists on server using JavaScript?

Sometimes, we want to check if image exists on server using JavaScript.

In this article, we’ll look at how to check if image exists on server using JavaScript.

How to check if image exists on server using JavaScript?

To check if image exists on server using JavaScript, we can use the Fetch API.

For instance, we write

const res = await fetch("https://via.placeholder.com/150", { method: "HEAD" });
if (res.ok) {
  console.log("Image exists.");
} else {
  console.log("Image does not exist.");
}

to see if the image at https://via.placeholder.com/150 can be loaded by calling fetch with the URL and an object that specify that we make a HEAD request.

If res.ok if true, the image is loaded successfully.

Otherwise, the image failed to load.

Conclusion

To check if image exists on server using JavaScript, we can use the Fetch API.