Currently when an error occurs while nextjs is rendering a page on the server side I can see in the browser network tab a document request that is getting a status 500 response and a white page with the message Application error: a client-side exception has occurred (see the browser console for more information).
.
I am using nextjs 14 and the page router.
For better understanding here is an example of my page/component structure:
export default function page(props: pageProps) {
return (
<div>
{/* MyComponent1 and Mycomponent2 do not
have any errors in it or its child components */}
<MyComponent1 />
<MyComponent2 />
{/* MyComponent3 has an error in it or its
child components */}
<MyComponent3 />
{/* Since in MyComponent3 is an error I want to
show an error component instead of MyComponent3
while this is rendered on the server */}
</div>
);
}
With my example above while nextjs renders a page with this component on it on the server side the whole page will result in the nextjs error page even though the error only happened in MyComponent3
. All other parts are working and do not contain any error.
My goal is to still get the HTML document from nextjs with the working parts of <MyComponent1>
and <MyComponent2>
but an error component rendered instead of <MyComponent3>
.
I am aware that react has Error boundaries, but these error boundaries are not working on the serverside while SSR. I tried to use try/catch
where I wrap the error prone code into the try
and render a fallback component in the catch
block. This seems to work within a single component but I want to wrap multiple components and its children at once. If I try to make a HOC
like for example withSsrErrorBoundary
and the try/catch
block in it the thrown errors in the wrapped component/s are not reaching the catch
block of my HOC
. I am trying to prevent writing try/catch
blocks manually everywhere into my codebase to reach my goal of rendering fallback components on the server side.
Is there any way to get error boundaries or an alternative working like I described above with SSR?
From the nextjs docs the App router error handling documentation page does exactly what i am looking for. But I need that for the page router.