Reputation: 11
I'm using async fetch request in page.tsx component similar to the below code
import { notFound } from 'next/navigation'
const PostViewPage = async ({params}) => {
const {slug} = params;
const resData = await fetch(`/api/post/${slug}`); //slug is a dynamic value
const postData = resData.json();
if(postData){
//rest code
}else{
notFound();
}
return (<>JSX Code</>)
}
If slug is not valid then it showing 404 Not Found page in browser. But, the request Status Code getting 200 in POSTMAN.
I want to throw 404 Page Not Found Error along with 404 Status Code. if any work around is there, Please guide me on this.
Upvotes: 1
Views: 2166
Reputation: 478
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.
if (!nodata) {
return NextResponse.rewrite(request.nextUrl.origin + '/404', {
status: 404,
});
}
app/404/page.tsx
and add return "Not found Page"
. Then update the middleware with if (!nodata) {
return NextResponse.redirect(request.nextUrl.origin + '/404');
}
Upvotes: 0
Reputation: 1136
It was caused by the loading.tsx
file, especially at the root folder or app. this is a known issue in next.js for now.
The only suggestion is that you can try to removing the root loading.tsx
file or suspense at root layout
Upvotes: 3
Reputation: 142
If that's all the content of your page.tsx
file, double check to be sure you're importing the notFound
function into your file.
import { notFound } from 'next/navigation'
You also need to have a app/not-found.tsx
in your root directory. This file renders a UI when the notFound function is thrown within a route segment.
Read more on the NEXT.js docs.
Upvotes: 0