How to throw 404 Not Found Error along with 404 status code in NextJS 13 App Router from page.jsx?

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.

  1. Add a middleware.ts file in the same level as your app directory
  2. Do async fetch call to your api to resolve the data.
  3. then conditionally you can have 2 options
  4. a. Stay in the same page and render the not_found content.
    if (!nodata) {
      return NextResponse.rewrite(request.nextUrl.origin + '/404', {
        status: 404,
      });
    }
  1. b. Redirect to your 404 page. For that create a file app/404/page.tsx and add return notFound(). Then update the middleware with
    if (!nodata) {
      return NextResponse.redirect(request.nextUrl.origin + '/404');
    }