What are layout, loading and error files in Next.js?

IntermediateNext.js interview questionBy , updated 17 November 2026

Short answer

They are special files in the Next.js App Router that each turn a folder into part of the UI. page is the route's content, layout wraps it and stays mounted across navigations, loading becomes a Suspense fallback, error becomes an error boundary and must be a Client Component, not-found renders when notFound() is called, and template is a layout that remounts on every navigation. Next.js nests them in a fixed order inside each segment.

The special files

File What it becomes Notes
page.tsx The UI for a URL A folder is only publicly routable when it has a page (or route) file
layout.tsx Shared wrapper that receives children Persists across navigation; the root layout must render <html> and <body>
template.tsx A wrapper with a unique key Remounts when its segment changes, resetting state and effects
loading.tsx A <Suspense> boundary's fallback Shown instantly while the segment's content streams in
error.tsx A React error boundary Must start with 'use client'
not-found.tsx UI for notFound() The root one also handles unmatched URLs
global-error.tsx Error boundary for the root layout Replaces the root layout, so it renders its own <html> and <body>
route.ts An HTTP endpoint (Route Handler) Cannot sit in the same folder as a page

All of these are Server Components by default, except error and global-error, which have to be Client Components.

How they nest

Inside one route segment, Next.js composes the files in this order:

<Layout>
  <Template>
    <ErrorBoundary fallback={<Error />}>
      <Suspense fallback={<Loading />}>
        <NotFoundBoundary fallback={<NotFound />}>
          <Page />
        </NotFoundBoundary>
      </Suspense>
    </ErrorBoundary>
  </Template>
</Layout>

For nested routes, the whole structure of a child segment goes where <Page /> would be in its parent. So app/dashboard/settings/page.tsx renders inside app/dashboard/layout.tsx, which renders inside app/layout.tsx, each with its own optional loading and error boundaries.

The order explains two rules people often get wrong:

  • error.tsx does not catch errors from the layout.tsx in the same folder, because the layout sits outside the boundary. An error in app/dashboard/layout.tsx is caught by app/error.tsx, the parent's boundary. Errors in the root layout need global-error.tsx.
  • loading.tsx does not cover the layout of the same folder. If the layout awaits uncached data, such as cookies() or an uncached fetch, the loading fallback cannot show for it. Wrap that part of the layout in its own <Suspense>, or move the fetch into the page.

Layouts keep state across navigation

When you navigate from /dashboard/settings to /dashboard/billing, only the part below app/dashboard/layout.tsx changes. The layout is not rerendered or remounted, so a sidebar's scroll position, an open accordion, a search input's text or a playing video in the layout survives. Next.js only fetches and renders the segments that changed, which is also why navigations feel fast.

That persistence has a cost: a layout does not rerender on navigation, so it cannot read searchParams, and it does not get the current pathname. Read those in a Client Component inside the layout with useSearchParams() or usePathname(), which update on navigation. A layout also cannot pass props to its children; the page fetches the data it needs, and memoised fetch or React.cache avoids a duplicate request.

If you want a wrapper that resets on every navigation, for example to rerun an enter animation or a page-view effect, use template.tsx. It receives a key per segment, so its Client Components remount when the segment changes.

loading.tsx: instant feedback

// app/dashboard/loading.tsx
export default function Loading() {
  return <DashboardSkeleton />;
}

On navigation the user immediately sees the shared layout plus this fallback, while the page renders on the server and streams in. Navigation stays interruptible, and the layout remains interactive. For finer control, place <Suspense> boundaries around individual slow components inside the page. Streaming and fetching patterns are covered in data fetching in the App Router.

error.tsx: must be a Client Component

// app/dashboard/error.tsx
"use client";

import { useEffect } from "react";

export default function Error({ error, retry }: { error: Error & { digest?: string }; retry: () => void }) {
  useEffect(() => {
    console.error(error); // or send it to your error tracking service
  }, [error]);

  return (
    <div role="alert">
      <h2>Something went wrong.</h2>
      <button onClick={() => retry()}>Try again</button>
    </div>
  );
}

It has to be a Client Component because React error boundaries are a client feature: they catch errors while rendering and swap in a fallback in the browser, and the fallback needs to be interactive so the user can retry. retry(), a stable prop since Next.js 16.3, refetches and rerenders the segment. A reset() prop also exists for clearing the error without refetching, and versions before 16.2 only had reset. In production, errors from Server Components arrive with a generic message and an error.digest you can match against server logs, so secrets in error messages do not leak.

Error boundaries catch rendering errors, not errors in event handlers or in async code you start yourself. For expected failures, such as validation in a form, return the error as a value from the Server Action instead of throwing. The general mechanism is in error boundaries in React.

not-found.tsx

Calling notFound() from next/navigation in a page or layout throws a special error that the nearest not-found.tsx renders. If the call happens before streaming starts, the response gets a 404 status; after streaming starts, the status is already 200. In both cases Next.js adds a noindex meta tag so search engines skip the page. The root app/not-found.tsx also handles any URL that matches no route.

Route groups

A folder in parentheses, such as (marketing) or (shop), organises routes without adding to the URL. app/(marketing)/about/page.tsx is served at /about. Groups let a set of routes share a layout that others do not get:

app/
  (marketing)/
    layout.tsx      // header and footer for public pages
    page.tsx        // /
    pricing/page.tsx
  (app)/
    layout.tsx      // sidebar for signed-in pages
    dashboard/page.tsx

Two groups must not resolve to the same path, and if each group has its own root layout (no app/layout.tsx), navigating between them causes a full page load. The App Router vs Pages Router answer compares this with _app and _document.

Practise it

Build Next.js App Router routing from files covers segments, route groups and conflicts. Implement an error boundary with retry/reset behavior is what error.tsx does, Build nested route loaders and actions shows nested layouts with pending UI, and Build a Suspense-based data-loading example and Reveal Suspense skeletons in order practise loading states.

Common follow-up questions

What is the difference between layout and template?

A layout persists across navigations within it and keeps its state. A template gets a new key when its segment changes, so its Client Components remount and their state and effects reset. Use a layout by default, and a template only when you need that reset.

Can a layout be a Client Component?

Yes, with 'use client', but you lose server-side data fetching in it and everything it imports joins the client bundle. Usually it is better to keep the layout on the server and put only the interactive part, such as a menu toggle, in a small Client Component.

Why does my error.tsx not show for an error in the layout?

Because the layout in the same folder sits outside that error boundary. Move the boundary up one level, or use global-error.tsx for the root layout.

Do I need a loading.tsx in every folder?

No. A boundary applies to its segment and everything below it. Add one where a route is slow enough to need a skeleton, and use inline <Suspense> for finer control.

Mistakes to avoid

  • Forgetting 'use client' at the top of error.tsx

  • Expecting a layout to rerender with new searchParams or pathname

  • Putting uncached data fetching in a layout and wondering why loading.tsx never appears

  • Using a template where a layout would do, and losing state on every navigation

  • Adding <head> tags by hand in the root layout instead of using the Metadata API

  • Creating two route groups that resolve to the same URL

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Build Next.js App Router routing from files: dynamic and catch-all segments, route groups and conflictsMedium40 min
  2. Implement an error boundary with retry/reset behaviorMedium35 min
  3. Build nested route loaders and actions: parallel loading, <Outlet>, pending UI, aborts and revalidationHard60 min
  4. Build a Suspense-based data-loading example with streaming SSR boundariesHard75 min
  5. Reveal Suspense skeletons in order without popcorn loading: nested boundaries and tail modesMedium40 min