Next.js: Can't get the status code on client side

Created on 30 Sep 2019  路  5Comments  路  Source: vercel/next.js

Bug report

Describe the bug

I use this code to get the status code:

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

but it doesn't always give me the status code.

To Reproduce

  1. Clone this repository: https://github.com/lcswillems/next-bug

  2. yarn dev

  3. Go to http://localhost:3000/djhfdkfjkh (an error page):

image

The status code is 404.

  1. Go to the home page by clicking on the link

  2. Go back to the error page by clicking on the back history arrow:

image

  1. The status code is now null.

image

Expected behavior

I would expect it to be 404.

System information

  • OS: linux
  • Browser (if applies) : chrome
  • Version of Next.js: 9.0.7

All 5 comments

getInitialProps only call server side.

No, it is called on server side and client side. In my example, it is called on both.

res is only available on the server side so it's expected and not a bug based on your code. However it seems that you're referring to /_error and that the documentation is slightly different from the actual getInitialProps we use internally. The correct method would be:

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

To split that out:

if(res && res.statusCode) {
  return res.statusCode
} else {
  if(err) {
    return err.statusCode
  }
  return 404
}

If /_error is rendered without an err it's a 404 basically. I'll update the docs!

Okay thank you for your fast answer!

Was this page helpful?
0 / 5 - 0 ratings