Q30: How do you return a 404 response from getStaticProps or getServerSideProps?
Return { notFound: true } from getStaticProps or getServerSideProps. Next.js immediately stops page rendering and serves the custom pages/404.js page with a 404 HTTP status code.
Returning 404 for Missing Database Records
export async function getStaticProps({ params }) {
const post = await fetchPost(params.id);
if (!post) {
return { notFound: true }; // Triggers 404 page
}
return { props: { post } };
}💡 If fetchPost returns null, notFound: true renders the 404 error page.
Key Takeaways
- Return
{ notFound: true }when target database items do not exist. - Renders the custom 404 error page automatically.
Knowledge Check
What happens when getStaticProps returns { notFound: true }?