Error boundaries help catch errors in parts of your app so the whole page does not break. They show a fallback UI instead of a blank or broken screen.
Client-side error boundaries in NextJS
import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return <div>Something went wrong.</div>; } return this.props.children; } }
Next.js uses React, so error boundaries follow React patterns.
Client-side error boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return <div>Oops! Something went wrong.</div>; } return this.props.children; } }
import React from 'react'; class ErrorBoundary extends React.Component { state = { error: null }; static getDerivedStateFromError(err) { return { error: err }; } render() { if (this.state.error) { return <div role="alert">Error: {this.state.error.message}</div>; } return this.props.children; } }
This example shows a component that throws an error inside an error boundary. Instead of crashing the whole app, it shows a friendly error message in red.
import React from 'react'; class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return <div role="alert" style={{ color: 'red' }}>Something went wrong.</div>; } return this.props.children; } } function BuggyComponent() { throw new Error('Bug!'); } export default function App() { return ( <main> <h1>My Next.js App</h1> <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> </main> ); }
React error boundaries are class components using static getDerivedStateFromError() and optionally componentDidCatch(). Next.js follows the same patterns.
Client-side error boundaries do not catch errors in event handlers or asynchronous code.
Use fallback UI that is accessible and clear to users.
Error boundaries catch errors in parts of your UI to prevent full app crashes.
They show fallback UI so users see a friendly message instead of a broken screen.
In Next.js, you can create client-side error boundaries using React class components.