Issue with Nextjs: getServerSideProps causing a blank page to display instead of redirecting to 404errorCode

I am facing an issue on my dynamic page where the external server returns a 404 error if the requested product is not found. However, when using getServerSideProps, instead of redirecting to a 404 page, it shows a blank page.

Below is the code snippet:

// pages/[slug].tsx

export const getServerSideProps: GetServerSideProps = async ({
  params,
  res,
}) => {
  const { product, relatedProducts } = await getProductDetail(
    params?.slug as string
  );

  if (res.statusCode === 404) {
    return {
      redirect: { destination: "/404", permanent: false },
    };
  }

  return {
    props: {
      product,
      relatedProducts,
    },
  };
};

I also tried using the notFound property:

if (res.statusCode === 404) {
    return {
      notFound: true
    };
  }

This issue is new to me as server redirection was working fine on other (static) pages. Any help would be highly appreciated.

Answer №1

Starting from NextJS 10, you no longer need to explicitly return your 404 page thanks to the introduction of the new flag notFound: true. This can be utilized in getStaticProps and getServerSideProps to automatically trigger either the default 404 page or a custom 404 page of your own.

// pages/[slug].tsx

export const getServerSideProps: GetServerSideProps = async ({
  params,
  res,
}) => {
  const { product, relatedProducts } = await getProductDetail(
    params?.slug as string
  );


  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }
  // if (res.statusCode === 404) {
    // return {
      // redirect: { destination: "/404", permanent: false },
    // };
  // }

  return {
    props: {
      product,
      relatedProducts,
    },
  };
};

Document References

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

What is the best way to troubleshoot an unresponsive button element to determine the listeners it has?

In a previous situation, I encountered an issue with the event modifier of a nested b-input not working as expected. To resolve this, I had to add .native because I was interacting with a component: b-dropdown(text="Actions") b-drop ...

In Rails 3, you can utilize JavaScript to submit a form_tag remotely, however ensure that it submits as

I am trying to implement a form_tag in rails 3 that can be submitted using ajax instead of html through javascript. Despite setting the form to submit as javascript, it still submits as html when clicking the submit button. - form_tag({:controller => " ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

Show information according to the selection made in the dropdown menu

Greetings! I am currently developing a web app using MVC .NET (C#) that includes a registration page for two types of users, type 1 and type 2. In the form, there is a dropdown list where users can select their type. When selecting type 2, I would like t ...

Guide for redirecting puppeteers' attention to a new pop-up interface

Currently, I am utilizing Puppeteer to carry out a test on a website. Upon clicking a button, a new popup browser window emerges displaying a report. Inside this new window lies data that I wish to extract. Is there a method for Puppeteer to switch its foc ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

Which specific values could cause the function to fail?

I am considering implementing the function provided below: function removeDuplicates(array){ var output=[],object={}; for(var index=0,length=array.length;index<length;index++){ object[array[index]]=0; } for(index in object){ ...

Vercel deployment unsuccessful: There was an issue with verifying the host key

Encountered an error while deploying a project on Vercel. This is the first time I've experienced this issue out of the 4 other projects hosted on Vercel: warning Pattern ["ethereumjs-abi@git+https://github.com/ethereumjs/ethereumjs-abi.git" ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

Can the SVG def element be modified?

In my SVG file, there is a defs element structured as follows: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 250 330" onclick="tweenGloss()"> <defs> <linearGradient id="grad" x1="174.6 ...

Tips for invoking an asynchronous function within an if condition?

When trying to maintain variables in the background.js of a Chrome extension, I encountered difficulties that require me to reinitialize some global variables. Here is the code snippet (view fiddle) I am using to demonstrate the issue: var temp = null; ...

How can I use JavaScript to update the content inside HTML tags with a specific string?

I have a situation where I need to replace a string in two different ways Input: Parameters-->string, AnnotationName, input Case 1: And I should input <i>Annotaion</i> as <b>input</b> Output : { displayData: `And I should inp ...

Issues Persist with Bootstrap Tree View - object passed but no output显示

After going through numerous discussions and solving several issues along the way, I have encountered a major problem where there is no output. As mentioned before, I am utilizing Bootstrap Tree View: To establish the hierarchical structure required for ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Tips on dividing a div into two separate pages when converting to PDF

I am working on an asp.net MVC project and I need to convert a HTML div into a PDF with two separate pages. Here is an example of my code: HTML Code <div class="row" id="mycanvas"> <p>This is the first part of my content.</p> <p ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

Logging in with Next Auth to a Keycloak account during testing in Cypress

Trying to create e2e tests with Cypress for my NextJs Application. Currently using Next Auth to log into my keycloak account via OAuth and displaying certain nav bar elements based on keycloak roles. To test this, I set up a test realm with test users. How ...

Regular expression for matching zero's following a decimal

I'm currently working on a regex method to validate decimals that only allow 2 numbers after the decimal point. For example, it should return true for 1.00 and false for 1.000, which it currently does. However, I also want it to return false for value ...

Execute the component function located within one page using another page

Can someone help me understand how to trigger OnSwipe from inside a different JS file named CardFooter.js? This file contains a button with an OnClick event that triggers OnSwipe from the preceding JS file called CardItem.js. Both of these files are includ ...