Verifying the Presence of an Image in the Public Directory of Next JS

My TypeScript Next.js project contains a large number of images in the public folder. I am wondering if there is a way to verify the existence of an image before utilizing the <Image /> component from next/image.

I have managed to achieve this using plain JavaScript, but TypeScript presents some complexities. Moreover, I encountered an error message from Next.js stating:

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.

Is there a way to determine whether /cars/audi-4.jpg exists? If not, I would like to utilize a default image instead.

Answer №1

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

Refer to the embedded comments for understanding the flow

import Image from "next/image";

// Utilizing HEAD method to inspect headers and status code
const isImageAvailable = async (imageName) => {
  return await fetch(`http://localhost:3000${imageName}`, {
    method: "HEAD",
  });
};

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

  // specifying the targeted image, location might vary
  let anyExistingImage = "/one.jpg";

  // Check if the desired image exists in the public folder, otherwise fallback to default image
  const result = await isImageAvailable(anyExistingImage);
  if (result.status === 200) {
    imageName = anyExistingImage;
  }

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

Directory structure includes Public folder along with page.js for Next.js 13 app,

https://i.stack.imgur.com/kxpEs.png

This information should provide clarity

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble displaying the week number in Angular Highcharts?

I am currently facing an issue with implementing highcharts in my Angular application that I am unable to resolve. My goal is to display the week number on the xAxis using the 'datetime' type. I came across this JSFiddle that seems to provide a ...

Having trouble bringing in a package into Next.js

After installing the Jodit Editor with npm -i jodit-react, I encountered an issue when trying to import it. Although the package was successfully added to the node modules, I couldn't import it. This is how I attempted to import the package: import J ...

The caniuse-lite data in Browserslist needs an update. To refresh it, kindly execute the following command: npx browserslist@latest --update

Every time I try to run my NextJs program, I keep encountering this error message: Browserslist: caniuse-lite is outdated. Please run: npx browserslist@latest --update-db Following the instructions, I entered npx browserslist@latest --update-db in the ter ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

Leverage generic types and allow acceptance of objects with arbitrary keys

Is it possible to allow the Use function argument type to accept any unknown key, as well as correctly type the keys from SomeGeneric? function Example (opt: { valid?: boolean }) { } type SomeGeneric = Parameters<typeof Example>[0] function Use(op ...

Importing a library dynamically in Next.js

I'm currently facing a challenge in dynamically importing a library into one of my next.js projects. The issue arises when I don't receive the default export from the library as expected. Initially, I attempted to import it the next.js way: impo ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Questioning the syntax of a TypeScript feature as outlined in the documentation

I have been studying the Typescript advanced types documentation, available at this link. Within the documentation, there is an example provided: interface Map<T> { [key: string]: T; } I grasp the concept of the type variable T in Map. However ...

Hold off on proceeding until the subscription loop has finished

Is there a way to verify that all results have been successfully pushed to nodesToExpand after running the for loop? The getFilterResult function is being called via an HTTP request in the nodeService service. for(var step in paths) { this.nodeSe ...

A Guide to Catching Targeted React Notifications in Sentry using Next.js

In my Next.js application, I have implemented Sentry for error tracking. While I have successfully set up Sentry to capture errors within my try/catch blocks, I am currently struggling with capturing specific errors and warnings at a global level in my sen ...

Ways to resolve the issue: ""@angular/fire"' does not contain the exported member 'AngularFireModule'.ts(2305) in an ionic, firebase, and

I am facing an issue while attempting to establish a connection between my app and a firebase database. The problem arises as I receive 4 error messages in the app.module.ts file: '"@angular/fire"' has no exported member 'AngularFi ...

Adjust the colors dynamically based on specific data within a loop

My task involves populating a table with data. Specifically, I am focusing on coloring the data in the first year column according to certain conditions. The desired outcome is as follows: +--------+------------+------+------+ | YEAR | 2022 | 2021 ...

Error: Page Not Found in NextJs version 13.4

My queries are twofold. Firstly, within my layout.tsx file, I have included a custom component <Navbar /> just above the {children}. Even though I have created a 404 page, the navbar still appears on that page. Is there a way to remove the navbar spe ...

Having trouble with Visual Studio 2015 not compiling TypeScript within an ASP.NET Core project?

Seeking assistance with my Angular app development setup in VS2015. Even though it is recognized as a TypeScript Virtual Project, I am facing issues getting the transpiled files into the wwwroot folder within my ASP.NET Core project. Here's an overvie ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

Retrieving the input value using ref in Vue 3 and TypeScript

It appears to be a straightforward issue, but I haven't been able to find consistent Vue 3 TypeScript documentation on accessing an input field and retrieving its value from within a function. <template> <Field type="text" ...

Navigate back to the initial page in Ionic2 using the navpop function

I have an application that needs to guide the user step by step. While I am aware of using navpop and navpush for navigating between pages, I am unsure about how to use navpop to go back to the first page. Currently, I am attempting to pop() twice if ther ...