19 Error handling in Next.js

Error handling is a crucial aspect in the development of robust and user-friendly web applications. Next.js provides various mechanisms to handle errors effectively and ensure a good user experience even in case of problems.

19.1 Default error page

Next.js automatically creates a default error page that is displayed when an error occurs. This page can be customized by creating a custom _error.js file in the pages directory.

19.1.1 Example of a custom error page:

function Error({ statusCode }) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} has occurred on the server`
        : 'An error has occurred on the client'}
    </p>
  );
}

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

export default Error;

19.2 Server-side error handling

During server-side execution, for example in getServerSideProps, errors may occur that should be handled appropriately. Here you can use try-catch blocks to catch errors and react accordingly.

19.2.1 Example:

export async function getServerSideProps(context) {
  try {
    // retrieve data
  } catch (error) {
    // error handling
    return { props: { error: 'Error retrieving data' } };
  }
}

19.3 Client-side error handling

On the client side, errors in React components can be handled using standard JavaScript techniques such as try-catch or error boundary components.

19.3.1 Error Boundaries in React

Error Boundaries are React components that catch errors in their child components and display a fallback UI instead of crashing the entire application.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>An error has occurred</h1>;
    }

    return this.props.children;
  }
}

19.4 API routes error handling

In API routes (pages/api) you can use Express-like error handling methods to manage errors. It is advisable to send consistent error responses to facilitate debugging and error handling on the client side.

19.4.1 Example:

export default function handler(req, res) {
  try {
    // API logic
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
}

19.5 Exercise: Creating a Next.js app with custom error handling

19.5.1 Task

Develop a simple Next.js application that makes an API request to an external source (e.g. https://jsonplaceholder.typicode.com/posts) to retrieve data. Implement custom error handling for the following scenarios: 1. server-side error when retrieving the data (e.g. API not reachable). 2. client-side error when displaying the data. 3. a user-defined error page for pages not found (404) and other unexpected errors.

19.5.2 Step-by-step guide

  1. Project initialization: Create a new Next.js project with npx create-next-app my-next-project.

2 Creating the pages: In the pages directory, create an index.js file for the main page and _error.js for the custom error page.

  1. API request: In index.js, use getServerSideProps to retrieve data from an external API and handle possible errors.

4 Data display and error handling: Implement logic to display data and catch client-side errors.

5 Custom error page: Create a custom error page in _error.js.