Errors in layouts
This page explains how to handle errors that occur in layout components and their limitations in Next.js.
Understanding layout errors
While error.tsx
effectively handles errors in nested child segments, it has an important limitation with layout errors. The error boundary cannot catch errors thrown in a layout.tsx
file within the same segment because the layout component exists above the error boundary in the component tree.
Example implementation
Consider this product route structure:
Directoryapp/
Directoryproducts/
Directory[productId]/
- error.tsx Won’t catch layout errors
- layout.tsx
- page.tsx
Here’s a layout component that might throw an error:
export default function ProductLayout({ children,}: { children: React.ReactNode;}) { // Simulate random errors const random = Math.random(); if (random < 0.5) { throw new Error("Error loading product layout"); }
return <div>{children}</div>;}
The error boundary in [productId]/error.tsx
won’t catch the error thrown in layout.tsx
because the layout component exists above the error boundary in the component tree.
Handling layout errors
To properly handle layout errors move the error boundary up to the parent segment:
Directoryapp/
Directoryproducts/
- error.tsx Can catch layout errors
Directory[productId]/
- error.tsx
- layout.tsx
- page.tsx
"use client";
export default function ProductError({ error, reset,}: { error: Error; reset: () => void;}) { return ( <div> <h2>Error in products section</h2> <p>{error.message}</p> <button onClick={reset}>Try again</button> </div> );}
Good to know
- Error boundaries can’t catch errors in the same segment’s layout
- Move error boundaries up to parent segments for layout error handling
- This behavior is intentional in Next.js’s error boundary implementation