Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify HTTP response code in next.js

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?

like image 498
Kostiantyn Ko Avatar asked Apr 20 '26 02:04

Kostiantyn Ko


1 Answers

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 };
};

like image 157
Kostiantyn Ko Avatar answered Apr 21 '26 15:04

Kostiantyn Ko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!