Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  146] [ 7]  / answers: 1 / hits: 11969  / 2 Years ago, tue, june 7, 2022, 12:00:00

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],
},
};
}

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?


More From » reactjs

 Answers
1

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],
},
};
}

[#101] Sunday, May 22, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;