completefrontend

Write the codeMedium

Write global-error.tsx for when the root layout itself fails

Leaf and Kettle's root layout checks the visitor's session before it renders, and when the session service is down, it throws. No error.tsx can catch that: every one of them sits inside the root layout. Write app/global-error.tsx, the screen Next.js shows in place of the whole app then. Its default export gets error, what was thrown, and retry, which fetches the route again and renders it if it works.

It replaces the root layout, so render the whole document: <html lang="en"> and <body>. Name the tab Leaf and Kettle is closed for a moment with React's <title> component. Show an <h1> with The tea shop is closed for a moment. and a Try again button that calls retry(). Never show the error's message.

Send each error to the tracker with logError(error) from @/lib/errors: once, after the screen renders, and again only when a different error arrives. And don't export metadata: Next.js refuses it in this file.

Write this: app/global-error.tsx
import type { Metadata } from "next";
import { logError } from "@/lib/errors";
 
export const metadata: Metadata = { title: "Leaf and Kettle is closed for a moment" };
 
export default function GlobalError({ error, retry }: { error: unknown; retry: () => void }) {
  logError(error);
 
  return (
    <main>
      <h1>The tea shop is closed for a moment.</h1>
      <button type="button">Try again</button>
    </main>
  );
}
lib/errors.ts (read-only)
/** Every error sent to the shop's error tracker, in order. */
export const logged: unknown[] = [];
 
/** Sends an error to the shop's error tracker. */
export function logError(error: unknown) {
  logged.push(error);
}
The tests your code must pass
  • renders the whole document, in English, with its own title
  • Try again calls retry
  • never shows the error's message
  • reports each error to the tracker once
  • doesn't export metadata, which a Client Component can't
  • is a Client Component, as global-error.tsx must be

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…