I'm currently building a NextJS 13.4.7 application with dynamic routes and a Headless cms coming from Contentful. All routes are open to use, as you can see in the screenshot below.
We want to get the data from the CMS. If there is no data for this page (slug) we need to throw a Notfound()
. Until this point everything works fine. However the Notfound() wont trigger a statuscode 404 on the server which will result in loss of SEO. The Notfound() custom page is triggered but no 404 status code is returned.
Is there a possibility to throw the notFound() with a 404 status code?
*edit added code
/app/[...slug]/page.tsx
export default async function ContentPageRoute({ params }) {
const pathname = `/${params.slug.join("/")}`;
const { pageCollection } = await getPageBySlug({
slug: pathname,
});
const page = pageCollection?.items[0];
if (!isDefined(page)) notFound();
return (
<Suspense fallback="Loading">
<ContentPage
breadcrumbs={
<Breadcrumbs style="containerWithSpaceBottom" pathname={pathname} />
}
page={page}
/>
</Suspense>
);
}
/app/notfound.tsx
export default function NotFound() {
return (
<p className="mt-5 mb-3 container-padding text-center">
De pagina kon helaas niet worden gevonden
</p>
);
}
With resulting in this request:
You need to rename your notfound.tsx
file to not-found.tsx
.
You didn't show how you import notFound
in your code, but make sure it's matching the one below:
import { notFound } from 'next/navigation'