- Published on
How to return a 404 Not Found page for dynamic routes in Next.js
- Authors
- Name
- Andreas Keller
- @itsakeller
For a Next.js blog you typically have a dynamic route posts/[slug].js
which fetches the blog posts from a headless CMS.
If the blog post is not found in the CMS, because it has e.g. been deleted or the slug has changed you can return a 404
status code and page by returning { notFound: true }
.
export async function getServerSideProps(context) {
const res = await fetch(`https://...`);
const data = await res.json();
if (!data) {
return {
notFound: true,
};
}
return {
props: {}, // will be passed to the page component as props
};
}
This works both for getStaticProps
and getServerSideProps
.
For getStaticProps
the page will return a 404
even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author.
Follow along as I'm building awesomereact.com in public.