Blog>
Snippets

Using getServerSideProps Error Handling

Provide an example of handling errors inside getServerSideProps in Next.js, including logging the error and redirecting to a custom error page.
export async function getServerSideProps(context) {
  try {
    // Attempt to fetch data from an API or another source
    const data = await fetchDataFromAPI();
    // If data fetching is successful, pass the data to the page via props
    return { props: { data } };
  } catch (error) {
    // Log the error to the server console
    console.error('Error fetching data:', error);
    // Redirect to a custom error page or the default 500 error page
    return {
      redirect: {
        destination: '/error', // Your custom error page path
        permanent: false
      }
    };
  }
}
This code represents a getServerSideProps function in a Next.js page which attempts to fetch data from an API. If it fails to fetch the data, it logs the error on the server-side console and then redirects the user to a custom error page.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Error Page</title>
  <style>
    /* Basic styling for the error page */
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
      font-family: Arial, sans-serif;
    }
    .error-container {
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="error-container">
    <h1>Something went wrong</h1>
    <p>We're sorry for the inconvenience. Please try again later.</p>
  </div>
</body>
</html>
This is the HTML structure with inline CSS for a custom-built error web page that can be used in conjunction with the getServerSideProps error handling. The page displays a message to the user indicating that an error has occurred.