The working approach is this comment https://github.com/vercel/next.js/issues/62228#issuecomment-2543853135
We should handle this in the middleware. The reason being we cannot modify the request headers to set 404 status in the page.tsx. it will throw error.
- Add a middleware.ts file in the same level as your app directory
- Do async fetch call to your api to resolve the data.
- then conditionally you can have 2 options
- a. Stay in the same page and render the not_found content.
if (!nodata) {
return NextResponse.rewrite(request.nextUrl.origin + '/404', {
status: 404,
});
}
- b. Redirect to your 404 page. For that create a file
app/404/page.tsx
and addreturn notFound()
. Then update the middleware with
if (!nodata) {
return NextResponse.redirect(request.nextUrl.origin + '/404');
}


