Mankesh
Mankesh

Reputation: 11

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

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.

POSTMAN REQUEST

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

Answers (3)

6by3
6by3

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.

  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 "Not found Page". Then update the middleware with
    if (!nodata) {
      return NextResponse.redirect(request.nextUrl.origin + '/404');
    }

https://imgur.com/a/HhGbWdo

Upvotes: 0

cantdocpp
cantdocpp

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

praizjosh
praizjosh

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

Related Questions