error.js
An error file defines an error UI boundary for a route segment.
'use client'; // Error components must be Client components
import { useEffect } from 'react';
export default function Error({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error);
}, [error]);
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// Attempt to recover by trying to re-render the segment
() => reset()
}
>
Try again
</button>
</div>
);
}
error
An instance of an Error
object. This error can happen on the server or the client.
reset
A function to reset the error boundary, which does not return a response.
error.js
boundaries must be Client Components.error.js
boundary will not handle errors thrown in a layout.js
component in the same segment because the error boundary is nested inside that layouts component.error.js
file in the layouts parent segment.error.js
called app/global-error.js
.error.js
boundaries do not currently work in next dev
development environment.global-error.js
To specifically handle errors in root layout.js
, use a variation of error.js
called app/global-error.js
located in the root app
directory.
'use client';
export default function GlobalError({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<html>
<head></head>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}
global-error.js
replaces the root layout.js
when active and so must define its own <html>
and <body>
tags.