Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js, redirect to 404 Not Found Page inside getServerSideProps [duplicate]

I am looking for a best practice in a server-side rendered page on handling an HTTP 404 if the requested page does not have an underlying server-side resource.

For example, let's assume the page requested is http://localhost:3000/places/5. In my SSG implementation:

export async function getServerSideProps(context) {
  const placeId = context.params.placeId;
  const places = await getPlace(placeId);
  
  if (!places.length) { /* is there anything here I can do to facilitate a 404? this place does not exist in the db */ }

  return {
    props: {
      places[0],
    },
  };
}

This should be self-explanatory, but if the requested id, in this case, 5 is not a place that's in my DB, how do I handle this as an HTTP 404?

like image 791
randombits Avatar asked Dec 05 '25 14:12

randombits


1 Answers

You can do that by returning an object like in the below code, with notFound: true. And here is a quote from the official doc:

The notFound boolean allows the page to return a 404 status and 404 Page.

export async function getServerSideProps(context) {
  const placeId = context.params.placeId;
  const places = await getPlace(placeId);

  if (!places.length) { 
   return {
     notFound: true,
   }
  }

  return {
    props: {
      places[0],
    },
  };
}
like image 121
yousoumar Avatar answered Dec 08 '25 03:12

yousoumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!