Throwing 404 in Next.js App Router Route Handlers doesn't show the 404 page

155 Views Asked by At

I have this route handler in Next.js:

export async function GET(_: Request, { params: { statusId } }: Params) {
  const tweetResponse = await queryClient<
    Tweet & Pick<User, "name" | "userImage" | "tag">
  >(`/tweets/${statusId}`, {
    cache: "no-store",
  });

  if (!tweetResponse.success) {
    if (tweetResponse.status === 404) notFound();

    throw new Error(tweetResponse.message);
  }

  const { tag, tweetId } = tweetResponse.data;

  redirect(`/${tag}/status/${tweetId}`);
}

If the tweet is found, it redirects to the correct page. but if it isn't, then the function should throw a 404 (as seen by calling the notFound() function).

The problem is, Next.js does return 404, but it doesn't show my custom 404 page. Infact, it doesn't show a 404 page at all, not my custom ones, nor the default next.js one, instead the browser doesn't even find a page to show so it just says "no webpage found at address "

How to fix this? I just need to show the 404 page (the custom one defined in not-found.tsx)

1

There are 1 best solutions below

0
Shiya Luo On

I ran into this exact situation. Invoking notFound() with route handler will only return 404 to the client component. What you need to do is try/catch that API call and manually redirect to /not-found.

Something like:

try {
  const response = await axios.get(`/api/tweets/${tweetId}`);
} catch (e) {
  router.push('/not-found');
}