How to use notFound() inside a app dir route handler
Unanswered
Giant panda posted this in #help-forum
Giant pandaOP
I'm trying to use notFound inside a route.ts file and it doesn't seem to work. I don't know if its because my route is async or anything
17 Replies
Giant pandaOP
export async function GET(request: Request) {
try {
doSomething()
} catch (error) {
notFound()
}
}The only way I can seem to achieve this is to redirect to a route that doesn't exist and let next pick it up
redirect("/error/404")
@Giant panda I'm trying to use notFound inside a route.ts file and it doesn't seem to work. I don't know if its because my route is async or anything
You can just return new Response(null, { status: 404 }) no?
It’s an api route so the 404 UI is not necessary
Only the status code is relevant
Giant pandaOP
It is an API route but I'm purposely wanting to send them to a UI on failure (its a callback URL as part of a UI journey)
@Giant panda It is an API route but I'm purposely wanting to send them to a UI on failure (its a callback URL as part of a UI journey)
how about calling
notFound(). that should redirect to your 404 page if you already have oneimport { notFound } from 'next/navigation'@Dayo how about calling `notFound()`. that should redirect to your 404 page if you already have one
although you may have to do this inside your pages file/where you're calling your api.
@Giant panda
export async function GET(request: Request) {
try {
doSomething()
} catch (error) {
notFound()
}
}
just checked and yes this one returned a 404 empty response as expected, that's exactly how api routes are supposed to behave
if you need the 404 UI then redirect to a non existent page is the best option
the other being returning a html response of the 404 UI
but you definitely wouldn't want to do that
Giant pandaOP
Yeah I ended up just doing a redirect to a made up URL page
though i get a weird scenario where locally in dev mode, that page keeps reloading every 2 secnds
i do get the 404 UI (not-found) page which is the end goal