next.js: Changing response status code in _error.js

changing response code in custom error page, not working.

This is content in pages/_error.js file.

import React from 'react'

function Error(props) {
    return (
       <div>
             my custom page
      </div>
    )
}

Error.getInitialProps = ({ req, res, err }) => {
     res.status = 200 // changing the response code here
     return {}
}

but status is always goes as 404. any suggestion?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 3
  • Comments: 17 (9 by maintainers)

Most upvoted comments

Also noticing this issue. I can set headers in the error page, but not the status code.

I have also tried this but not getting the custom page

Custom Page

image

but getting this page

next js 404 page

image

This is code for _error.js

import { Result, Button } from "antd";
import Link from "next/link";
import { AiFillHome } from "react-icons/ai";

let Error = ({ statusCode }) => {
  console.log("client side: ", statusCode);
  let errorMessage = "";
  if (statusCode === 404) {
    errorMessage = "Sorry, the page you visited does not exist.";
  } else {
    errorMessage = "Sorry, something went wrong";
  }
  return (
    <>
      <Result
        status={statusCode}
        title={statusCode}
        subTitle={errorMessage}
        extra={
          <Button type="primary">
            <Link href="/">
              <a>
                <AiFillHome style={{ marginRight: "10px" }} /> Home
              </a>
            </Link>
          </Button>
        }
      />
    </>
  );
};

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

export default Error;

and calling error code

import ErrorPage from "next/error";
import React from "react";

export default ({ data }) => {
  const [errorFound, setErrorFound] = React.useState(true);

  if (errorFound) {
    return <ErrorPage statusCode={404} />;
  }

  return <div>This page content</div>;
};

export const getStaticProps = async (context) => {
// get Static page data
  return {
    props: {
data: JSON.parse(JSON.stringify(data)),
    },
  };
};
export const getStaticPaths = async (context) => {
  return {
    paths: [],
    fallback: "blocking",
  };
};

🙏 PLEASE TELL ANY WRONG I HAVE DONE IN CODE 🙏