Blog>
Snippets

Error Boundaries for Server Side Rendering (SSR)

Demonstrate setting up an error boundary in Next.js to catch and handle errors that occur during server-side rendering.
import React from 'react';

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

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

  componentDidCatch(error, errorInfo) {
    // Log the error to an error reporting service
    logErrorToService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // Render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}
This is a React Error Boundary component, which is designed to catch JavaScript errors anywhere in the child component tree and log them, then display a fallback UI instead of the component tree that crashed. Replace `logErrorToService` with the actual error logging function.
import { ErrorBoundary } from './ErrorBoundary'; // Import the ErrorBoundary component
import App from './App';

// Wrap the root component in the ErrorBoundary
const RootComponent = () => (
  <ErrorBoundary>
    <App />
  </ErrorBoundary>
);

export default RootComponent;
This code shows how to use the ErrorBoundary component by wrapping the root component of the application. Replace `App` with the actual root component of your Next.js project.
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    try {
      const initialProps = await Document.getInitialProps(ctx);
      return { ...initialProps };
    } catch (error) {
      // Handle the error, possibly logging it as well
      handleDocumentError(error);
      // Return an error state to render an error page or partial content
      return { hasError: true, error }; 
    }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          {this.props.hasError ? (
            /* Replace with actual error component or UI message */
            <div>Error occurred while rendering</div>
          ) : (
            <Main />
          )}
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
In a Next.js custom Document, the `getInitialProps` method is used to catch errors during server-side rendering and log them or return an error state. The `hasError` flag can be used to conditionally render an error page or UI message.