How to return 404 page from api handler? #39859
Replies: 6 comments 2 replies
-
This is an interesting use case. The API routes could be modelled as an escape hatch to serve different types of content from your Next.js applications. They are not limited to that, but we could think of them like that for this use case. There's a few implications, first of all, we do not send any of the _document, nor _app, resulting HTML. It follows that no React framework is served either, nor any CSS used by the app. We are effectively decoupled. To recreate a page we'd need to serve at the very least, the CSS and HTML structure. I don't think there's a built-in way to accomplish this. From what I know, |
Beta Was this translation helpful? Give feedback.
-
So how is it handled by default? I'm not sure I'm digging in the right place, but there's something like |
Beta Was this translation helpful? Give feedback.
-
Ok. My current 2 workarounds:
Fetch response could be cached if top-notch 404 page performance is needed 😉 |
Beta Was this translation helpful? Give feedback.
-
I want to know the same thing but for the custom server. Is there a way to deliberately render the 404 page? I tried using |
Beta Was this translation helpful? Give feedback.
-
I'd also like to know how this might be achieved. I'm currently using this function:
as my endpoint is only expecting to receive post requests, which are handled correctly using the But this doesn't return the 404 page. It just shows the browser's default 404 page. I'm guessing since this has been unanswered for so long that it isn't actually possible, which sucks. |
Beta Was this translation helpful? Give feedback.
-
I got this to work:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
By default, all non-existing paths (including frontend and API) return the default 404 Next.js page.
It can be customized in
pages/404.js
file.It's possible to return that default/customized error page from
getServerSideProps
by returninghttps://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#notfound
But what about API handlers?
Response helper has no
error
method. The body has to be sent manually and JSX obviously doesn't work there.https://nextjs.org/docs/api-routes/response-helpers
I thought about
but it's not an ideal solution...
How to send the default Nextjs error page as a response in API handler?
Beta Was this translation helpful? Give feedback.
All reactions