🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js template.tsx and global-error.tsx

template.tsx re-mounts its children on every visit. global-error.tsx is the last-resort page when even the layout fails.

The template stamps the time

The template prints the time it ran, then the page. A new time means a new run.

export default function BooksTemplate({ children }: { children: React.ReactNode }) {
  return (
    <div>
      <p>Books template, loaded at {new Date().toLocaleTimeString()}</p>
      {children}
    </div>
  );
}

Two visits, two times

The check visits /books twice. Each visit shows a new time, five seconds later.

curl -s http://localhost:3000/books | grep -oE "Books template, loaded at .{0,18}"
curl -s http://localhost:3000/books | grep -oE "Books template, loaded at .{0,18}"

The global error file

The file starts with "use client" and carries its own html and body. It is the last resort when the root layout fails.

"use client";

export default function GlobalError() {
  return (
    <html>
      <body>
        <h1>Bookshelf is down</h1>
      </body>
    </html>
  );
}

Example

console.log("Visit 1: Books template, loaded at 8:14:48 PM");
console.log("Visit 2: Books template, loaded at 8:14:53 PM");
console.log("Broken root layout: 500, Bookshelf is down");

Key points

  • Template: a file like a layout, but it runs again on every visit
  • A layout keeps its state between visits. A template starts fresh each time.
  • Two visits to /books showed two times: 8:14:48 PM, then 8:14:53 PM. The template ran again.
  • In production /books is a static page, so the time freezes at the build.
  • global-error.tsx catches errors in the root layout itself. It carries its own html and body tags.
  • A broken root layout answers 500. The text "Bookshelf is down" sits in the compiled error chunk.

In this example, two visits show the template running twice. The first visit stamps 8:14:48 PM, and the second stamps 8:14:53 PM, five seconds later. In production the books page is static, so the time would freeze at the build. A broken root layout answers 500, and "Bookshelf is down" sits in the compiled error chunk.

Note

global-error.tsx must start with "use client", a line the next section explains. Its text shows in the browser, not in curl.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

How is template.tsx different from layout.tsx?