Next.js offers a flexible approach to managing error pages through the creation of a pages/_error.js file. This file serves as a universal error handler for your application.
Here’s how you can implement it:
function Error({ statusCode }) {
return (
<p>
{statusCode
? `A ${statusCode} error occurred on the server`
: 'An error happened on the client'}
</p>
);
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
This setup allows for dynamic error handling. The component checks whether the error originated on the server (with a status code) or the client and displays an appropriate message. It uses getInitialProps to retrieve the error’s status code, defaulting to 404 if no specific code is available.