So far AgendaViva only handles the happy path. If the data takes a while, it shows a paragraph; if the slug doesn't exist, another one; and if the query fails, the page breaks. A real application spends a lot of time in those states, and Next.js reserves a file for each of them: loading.tsx, not-found.tsx, error.tsx and global-error.tsx.

What matters isn't memorizing their names but knowing where to place them: each one replaces part of the tree and leaves what's above it intact. You'll also see a consequence of sending the response in chunks: the HTTP status is decided at the start, before it's known whether the resource exists.

  1. Loading states

loading.tsx isn't a new mechanism. Next.js wraps the page and everything below its segment in a <Suspense> whose fallback is that component:

// What having loading.tsx next to page.tsx amounts to
<Layout>
  <Suspense fallback={<Loading />}>
    <Page />
  </Suspense>
</Layout>

That's why it allows the page to be async and wait directly: it's already inside a boundary. And that's why it doesn't cover the waits in the layout.tsx of its folder, which sits outside.

The component receives no props, it's part of the shell that gets prefetched and, while it's displayed, the layouts remain usable: the user can go to another section without waiting.

1.1. loading.tsx or Suspense

loading.tsx <Suspense> in the page
Scope The whole page and its descendants The block you choose
What's visible instantly Layouts and the skeleton Also headings, text and everything static
Multiple waits A single fallback for all of them Each one resolves on its own
The page Can be async Composes; the children wait

The documentation recommends preferring explicit boundaries close to the data. A loading.tsx high up in the tree is a valid boundary, but it absorbs any wait that slips through and turns the whole page into a skeleton without anything warning you. Keep it for pages where everything depends on the same data.

The public pages already use <Suspense> and will stay that way. The dashboard's list is a good candidate for loading.tsx, and it needs data.

1.2. The dashboard's list

The dashboard queries see drafts and events under review, so they go in a module separate from the public one. There are no sessions yet: until module 8, the organizer will be hard-coded.

// lib/data/dashboard.ts
import { events, simulateQuery } from '@/lib/data/memory'
import type { AgendaEvent } from '@/lib/types'

// Will be replaced by the session user in module 8
export const PLACEHOLDER_ORGANIZER_ID = 'usr-02'

export async function listDashboardEvents(organizerId: string): Promise<AgendaEvent[]> {
  await simulateQuery()
  return events
    .filter((event) => event.organizerId === organizerId)
    .sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime())
}
// lib/format.ts (addition; also import the EventStatus type)
export const STATUS_LABELS: Record<EventStatus, string> = {
  draft: 'Draft',
  review: 'In review',
  published: 'Published',
  canceled: 'Canceled',
}
// app/(dashboard)/dashboard/events/page.tsx
import { listDashboardEvents, PLACEHOLDER_ORGANIZER_ID } from '@/lib/data/dashboard'
import { STATUS_LABELS, formatDateTime } from '@/lib/format'

export default async function DashboardEventsPage() {
  const events = await listDashboardEvents(PLACEHOLDER_ORGANIZER_ID)

  return (
    <>
      <h1 className="mb-6 text-2xl font-bold">My events</h1>
      <table className="w-full text-left">
        <thead>
          <tr>
            <th scope="col">Title</th>
            <th scope="col">Date</th>
            <th scope="col">Status</th>
          </tr>
        </thead>
        <tbody>
          {events.map((event) => (
            <tr key={event.id}>
              <td>{event.title}</td>
              <td>{formatDateTime(event.startsAt)}</td>
              <td>{STATUS_LABELS[event.status]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  )
}

This page waits at its top level. Without loading.tsx it would throw the prerendering error you already know. With it, it's correct. The skeleton will be shared:

// components/list-skeleton.tsx
export function ListSkeleton({ items = 4 }: { items?: number }) {
  return (
    <div role="status">
      <span className="sr-only">Loading…</span>
      <div aria-hidden className="grid gap-4">
        {Array.from({ length: items }, (_, index) => (
          <div key={index} className="h-12 animate-pulse rounded-lg bg-slate-200" />
        ))}
      </div>
    </div>
  )
}
// app/(dashboard)/dashboard/events/loading.tsx
import { ListSkeleton } from '@/components/list-skeleton'

export default function DashboardEventsLoading() {
  return <ListSkeleton items={8} />
}

The skeleton should take up roughly the same space as the content, so that the page doesn't jump when the data arrives. The visually hidden text informs screen reader users.

Keep the scope in mind: this loading.tsx will also wrap /dashboard/events/new and /dashboard/events/[id]/edit. If it doesn't suit one of them, that page will get its own, closer one.

1.3. When only the parameters change

In 02-03 you saw that, when filtering, the previous list stays until the new one arrives. That's React's behavior in a transition: it avoids hiding content that has already been shown. It's usually pleasant, but with a new filter the old results can be confusing. To make React treat the content as different and show the fallback again, you give the <Suspense> a key.

The key depends on the filters, which have to be read first. The component is split in two, and only the inner one queries:

// app/(public)/events/page.tsx (from EventResults onwards)
async function EventResults({ searchParams }: Pick<Props, 'searchParams'>) {
  const filters = normalizeFilters(await searchParams)

  return (
    <Suspense key={createEventsUrl(filters)} fallback={<ListSkeleton />}>
      <EventList filters={filters} />
    </Suspense>
  )
}

async function EventList({ filters }: { filters: EventFilters }) {
  const { events, total, page, totalPages } = await listEvents(filters)

  if (filters.page !== page) {
    redirect(createEventsUrl({ ...filters, page }))
  }

  return (
    <>
      <p className="mb-4 text-sm text-slate-600">
        {total === 0 ? 'No events match your search.' : `${total} events`}
      </p>
      <ul className="grid gap-4 sm:grid-cols-2">
        {events.map((event) => (
          <li key={event.id}>
            <EventCard event={event} />
          </li>
        ))}
      </ul>
      <Pagination
        page={page}
        totalPages={totalPages}
        createHref={(pageNumber) => createEventsUrl({ ...filters, page: pageNumber })}
      />
    </>
  )
}

Import ListSkeleton and the EventFilters type. The <Suspense> in EventsPage stays: it covers reading searchParams on the initial load.

  1. Not found pages

The notFound() function from next/navigation stops the component and shows the nearest not-found.tsx going up the tree. Like redirect, it works by throwing a special error, and its return type is never: after the check, TypeScript knows the value exists.

// app/(public)/events/[slug]/page.tsx (EventContent)
async function EventContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const event = await getEventBySlug(slug)
  if (!event) notFound()

  return <EventDetails event={event} />
}
// app/(public)/events/[slug]/not-found.tsx
import Link from 'next/link'

export default function EventNotFound() {
  return (
    <>
      <h1 className="text-2xl font-bold">We couldn't find this event</h1>
      <p className="mt-2">The address may be misspelled, or the event may have been removed.</p>
      <Link href="/events" className="mt-4 inline-block underline">
        See the full guide
      </Link>
    </>
  )
}

Do the same in venues/[slug]: if (!venue) notFound() and its own not-found.tsx, with a link to /venues.

The data function still returns null. The page is what decides that this is a 404, because another consumer may want something different: in the 02-05 modal it will show a message.

For addresses that don't match any route, app/not-found.tsx is used. Only the root layout sits above it, so it doesn't get the (public) header and writes its own <main>:

// app/not-found.tsx
import Link from 'next/link'

export default function NotFound() {
  return (
    <main className="mx-auto w-full max-w-xl flex-1 px-4 py-16">
      <h1 className="text-3xl font-bold">Page not found</h1>
      <p className="mt-2">This address doesn't exist on AgendaViva.</p>
      <Link href="/" className="mt-4 inline-block underline">
        Back to the home page
      </Link>
    </main>
  )
}

Keep these files lightweight. Next.js sends them with every route in their segment, not only when there's a 404; the root one travels with the entire site. Server Components and Link are enough.

2.1. The HTTP status and streaming

Open /events/does-not-exist with the browser's developer tools: you'll see the not found page, but the response status is 200. It isn't a bug. HTTP status codes travel in the headers, and the headers are sent before the body. With Cache Components, Next.js sends the shell first; by the time EventContent discovers that the event doesn't exist, the 200 has already gone out.

sequenceDiagram
    participant N as Browser
    participant S as Server
    N->>S: GET /events/does-not-exist
    S-->>N: 200 and the shell
    S->>S: Query: null, notFound()
    S-->>N: Not found UI and noindex meta tag
Situation Status What Next.js adds
URL that doesn't match any route 404 noindex
notFound() during prerendering 404 noindex
notFound() during the request, after the shell 200 noindex in the streamed HTML
Error in a component after the shell 200 The error.tsx UI
redirect() after the shell 200 A redirecting meta tag

For people there's no difference. For search engines, the noindex tag prevents them from indexing the address, although some tools may flag it as a "soft 404". If you need the exact status, the check has to happen before the response starts: when prerendering with the known slugs (05-05) or in the proxy (07-02). Don't try to achieve it by removing the <Suspense> boundaries: the documentation warns that, with Cache Components, not even a route marked as blocking changes the 200.

  1. Expected and unexpected errors

Before writing error.tsx, it's worth separating two kinds of problem.

Expected Unexpected
Examples Incomplete form, capacity reached, nonexistent resource The database doesn't respond, a programming bug
Part of normal use Yes No
How it's expressed Return value: null, a message, notFound() Exception
Who handles it The calling component An error boundary

If capacity runs out while someone is booking, you don't throw an error: you return a result that the UI knows how to render (module 6). If the query fails, there's nothing useful to do in the component: you let the exception propagate. Wrapping every read in try/catch to return an empty list is worse than doing nothing, because the user will think there are no events.

  1. error.tsx

error.tsx is a React error boundary that Next.js places around the page and the layouts below it. It must be a client component. It receives these props:

Prop Type Content
error unknown Whatever was thrown
retry () => void Requests the boundary's content from the server again and re-renders it
reset () => void Clears the error and re-renders without fetching data

retry has been stable since version 16.3. In earlier code you'll see it as unstable_retry, and in older examples only reset, which doesn't recover from Server Component errors because it doesn't repeat the request. Use retry.

The unknown type matters too. In JavaScript you can throw anything, so you have to check before reading message. With server errors, moreover, the original message doesn't arrive in production: Next.js replaces it with a generic one, so as not to leak internal details, and adds a digest. That identifier also appears in the server log and lets you match the two.

Since there will be several error.tsx files, the UI will be shared. ErrorInfo is the type exported by next/error with those three props:

// components/error-notice.tsx
'use client'

import { useEffect } from 'react'
import type { ErrorInfo } from 'next/error'

type Props = Pick<ErrorInfo, 'error' | 'retry'> & { title: string }

function getReference(error: unknown): string | null {
  if (error instanceof Error && 'digest' in error && typeof error.digest === 'string') {
    return error.digest
  }
  return null
}

export function ErrorNotice({ error, retry, title }: Props) {
  const reference = getReference(error)

  useEffect(() => {
    console.error(error)
  }, [error])

  return (
    <div role="alert" className="rounded-lg border border-red-300 bg-red-50 p-6">
      <h2 className="text-xl font-semibold">{title}</h2>
      <p className="mt-2">Something went wrong on our end.</p>
      {reference && <p className="mt-2 text-sm">Reference: {reference}</p>}
      <button type="button" onClick={() => retry()} className="mt-4 underline">
        Try again
      </button>
    </div>
  )
}
// app/(public)/error.tsx
'use client'

import type { ErrorInfo } from 'next/error'
import { ErrorNotice } from '@/components/error-notice'

export default function PublicError({ error, retry }: ErrorInfo) {
  return <ErrorNotice error={error} retry={retry} title="We can't show this page" />
}

Create an identical one in app/(dashboard)/dashboard/error.tsx, named DashboardError and with the title "We can't show the dashboard". Its position decides what survives: since it's under DashboardLayout, the side menu stays visible and the organizer can go to another section.

The console.error is temporary; in 10-05 errors will be sent to an observability service.

4.1. Trying it out

Temporarily add a random failure to listEvents, after await simulateQuery():

if (Math.random() < 0.5) throw new Error('Simulated database failure')

Math.random() is another value that can't be read during prerendering; here it's acceptable because it comes after io(), that is, already within the request. In development, the Next.js error overlay appears on top with the original message; close it to see your UI. With npm run build and npm run start you'll see the production result: notice, reference and button. When you click "Try again", the list will eventually appear. Remove the line afterwards.

Notice what has been replaced: all of the (public) content, including the heading and the form, because the nearest boundary is at that level. If you want only the list to be replaced, you need a smaller boundary.

4.2. Boundaries inside a page: catchError

error.tsx works per segment. To protect a specific block, next/error provides catchError, which takes a notice component and returns another one that wraps its children:

// components/error-boundary.tsx
'use client'

import { catchError, type ErrorInfo } from 'next/error'
import { ErrorNotice } from '@/components/error-notice'

function Notice({ title }: { title: string }, { error, retry }: ErrorInfo) {
  return <ErrorNotice error={error} retry={retry} title={title} />
}

export const ErrorBoundary = catchError(Notice)
// app/(public)/events/page.tsx (in EventsPage)
<ErrorBoundary title="We can't load the events">
  <Suspense fallback={<ListSkeleton />}>
    <EventResults searchParams={searchParams} />
  </Suspense>
</ErrorBoundary>

Notice first receives its own props and then the error information. Compared with a hand-written error boundary, catchError lets the special errors from redirect() and notFound() pass through, and it clears itself when you navigate to another route.

Keep the order: the error boundary goes outside the <Suspense>. That way, a failure replaces the whole block and doesn't leave an orphaned skeleton.

4.3. What they don't catch

Error boundaries catch failures during rendering. They don't catch those that happen in an event handler or in later asynchronous code, such as a setTimeout: there you use try/catch and store the error in state. An exception inside startTransition does reach the nearest boundary.

  1. global-error.tsx

If the root layout itself fails, there's no frame left to render the notice in. app/global-error.tsx replaces the entire document, and that's why it writes <html> and <body>:

// app/global-error.tsx
'use client'

import type { ErrorInfo } from 'next/error'

export default function GlobalError({ retry }: ErrorInfo) {
  return (
    <html lang="en">
      <body style={{ fontFamily: 'system-ui, sans-serif', padding: '2rem' }}>
        <title>AgendaViva error</title>
        <h1>AgendaViva is unavailable</h1>
        <p>We're working on a fix.</p>
        <button type="button" onClick={() => retry()}>
          Try again
        </button>
      </body>
    </html>
  )
}

It doesn't include your global styles, hence the inline styles, and it doesn't support metadata, because it's a client component: use React's <title> element. Don't import anything into it that could be the cause of the failure.

flowchart TD
    A["Failure in EventLocation"] --> B["Nearest ErrorBoundary, if any"]
    B -- none --> C["app/(public)/error.tsx"]
    D["Failure in PublicLayout"] --> E["app/error.tsx, if it exists"]
    E -- doesn't exist --> G["app/global-error.tsx"]
    F["Failure in RootLayout"] --> G

AgendaViva has no app/error.tsx: a failure in PublicLayout or in ManagementLayout reaches global-error.tsx. Since those layouts don't fetch data, that's reasonable. If they ever do, it'll be worth adding one.

Two more states remain: someone who hasn't signed in and someone who doesn't have permission. Next.js provides unauthorized() and forbidden(), with their unauthorized.tsx and forbidden.tsx files, but they're experimental and the documentation doesn't recommend them in production. In module 8 we'll use redirect and notFound.

Common Mistakes and Tips

  • Putting a loading.tsx at the root "just in case". It absorbs every wait and replaces entire pages.
  • Expecting loading.tsx to cover its layout.tsx. The layout is outside it.
  • Forgetting 'use client' in error.tsx or in global-error.tsx.
  • Using reset to retry a server read. It doesn't repeat the request; use retry.
  • Showing error.message to the user. In production it's generic, and in development it can reveal details.
  • Catching a notFound() or a redirect() with try/catch. They're exceptions; call them outside the try.
  • Returning an empty list when the query fails. It turns an outage into false data.
  • Checking for a 404 only by the HTTP status. After the shell it will be 200 with noindex.

Exercises

Exercise 1: who responds

State what the user sees in each case with the files from this lesson: (a) they visit /events/xyz; (b) they visit /workshops; (c) listVenues throws an error on /venues; (d) listDashboardEvents takes five seconds; (e) RootLayout throws an error.

Solution

  • (a) events/[slug]/not-found.tsx, with the public header and footer, and a 200 status with noindex.
  • (b) app/not-found.tsx, without a header, with a 404 status: no route matches.
  • (c) (public)/error.tsx, inside PublicLayout.
  • (d) dashboard/events/loading.tsx for five seconds, with the side menu usable.
  • (e) global-error.tsx, which replaces the document.

Exercise 2: protecting the venue on the event page

If the venue query fails, the whole event page is replaced by the (public) notice. Make the event stay visible and only the location line fail.

Solution

// app/(public)/events/_components/event-details.tsx
<ErrorBoundary title="We can't load the venue">
  <Suspense fallback={<p>Loading the venue…</p>}>
    <EventLocation venueId={event.venueId} />
  </Suspense>
</ErrorBoundary>

EventDetails is still a Server Component: it can use a client component as a wrapper and pass it server children. The reason why is in 03-03. The change is a good one and the course keeps it.

Exercise 3: reviewing error handling

Find the problems in this component and rewrite it.

async function VenueContent({ params }: Pick<Props, 'params'>) {
  try {
    const { slug } = await params
    const venue = await getVenueBySlug(slug)
    if (!venue) notFound()
    return <h1>{venue.name}</h1>
  } catch (error) {
    return <p>{String(error)}</p>
  }
}

Solution

  • notFound() is inside the try: the catch traps its special error and the 404 isn't shown.
  • A database failure is shown as is to the visitor, with possible internal details.
  • Since it isn't propagated, the error doesn't reach error.tsx, there's no retry and it isn't logged either.
async function VenueContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  const venue = await getVenueBySlug(slug)
  if (!venue) notFound()

  return <h1>{venue.name}</h1>
}

Without the try, each problem reaches whoever knows how to handle it: a missing resource goes to not-found.tsx; an outage, to error.tsx.

Conclusion

The state files are React boundaries placed by convention, and their position decides what gets replaced and what stays. loading.tsx covers pages that depend entirely on one piece of data; for everything else, use <Suspense> next to the wait. Expected cases are returned or expressed with notFound(); unexpected ones are thrown and caught by error.tsx, catchError or, as a last resort, global-error.tsx. And since the shell goes out first, the HTTP status doesn't always tell the whole story.

One piece of routing remains. So far each URL shows a single page inside its layouts. In the next lesson, Parallel and Intercepting Routes, you'll show several at once in the dashboard and open events in a quick view on top of the guide, without giving up their own address.

© Copyright 2026. All rights reserved