Handling Errors in Root Layouts - Next.js
The root app/error.js boundary does not catch errors thrown in the root /app, so how do you handle it?
Well, of course, the team in Next.js already has it solved.
You can use a variation of the error.js called global-error.js in your /app folder.
You can read more on the Next.js docs, but in this article, I'll show you how to get started quickly.
Creating a global-error.js
I'll give you the quick copy-paste snippets to get you started and to ensure you have the final fallback if all else fails:
Here's a JS version:
'use client'
// optional, use Sentry to report errors or whatever tool you use to catch errors
import * as Sentry from "@sentry/nextjs";
import NextError from "next/error";
import React from "react";
import { useEffect } from "react";
export default function GlobalError({ error }) {
// optional useEffect to capture the errors and report them
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<html>
<body>
<h1>Something went wrong!</h1>
{/* This is the default Next.js error component, but it doesn't allow omitting the statusCode property yet. */}
<NextError statusCode={undefined} />
</body>
</html>
)
}
And a TS version:
'use client'
// optional, use Sentry to report errors or whatever tool you use to catch errors
import * as Sentry from "@sentry/nextjs";
import NextError from "next/error";
import React from "react";
import { useEffect } from "react";
export default function GlobalError({
error
}: {
error: Error & { digest?: string }
}) {
// optional useEffect to capture the errors and report them
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<html>
<body>
<h1>Something went wrong!</h1>
{/* This is the default Next.js error component, but it doesn't allow omitting the statusCode property yet. */}
<NextError statusCode={undefined as any} />
</body>
</html>
)
}
Note: Since this error replaces your root layout if it's called, you must also wrap it with a <HTML> and <body> tag.
Capture your errors!
In my examples, I'm also using Sentry to catch the errors so that I know about them and can inspect them.
I just wanted to share some of this logic in case you want to try something similar since it's hard to know what to fix if you aren't reporting crashes. 🔧
I hope this helped!
