I have a Next.js v12 application written in TypeScript.
I have a _error.tsx page providing custom UI experience for various errors, including 410, 404 and other ones. The issue is, whatever API error triggers the appearance of this page on the server-side, the client browser GETs this page from server with the HTTP status code of 500.
How could I customize that status code, so that for example the page for 410 actually has the HTTP status code of 410?
Well, I managed to find the solution on my own.
It's a little bit counter-intuitive, but to get the desired behavior you should just directly set the value of statusCode of the res object coming into getInitialProps of the said _error.tsx page.
Along these lines:
ErrorPage.getInitialProps = ({ res, err }: NextPageContext) => {
const statusCode =
(err as AxiosError)?.response?.status ?? res?.statusCode ?? err?.statusCode ?? undefined;
if (res && statusCode) {
res.statusCode = statusCode;
}
const text = String(res?.statusMessage || err?.message || err);
return { statusCode, text };
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With