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.
Clone this repository: https://github.com/lcswillems/next-bug
yarn dev
Go to http://localhost:3000/djhfdkfjkh (an error page):

The status code is 404.
Go to the home page by clicking on the link
Go back to the error page by clicking on the back history arrow:


I would expect it to be 404.
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!
Fixed in https://github.com/zeit/next.js/commit/0bcd1fc39bb07f67b94238a0e867e9c3fe73a163
Good catch! Thanks 馃檹
Okay thank you for your fast answer!