Skip to content
Visual explainer 4h to learn 5 steps

File-based routing, layouts & navigation

Build nested layouts, dynamic routes, loading and error states.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 20 of 36

In short

In the Next.js App Router, folders inside app define URL segments and page.tsx makes a segment visitable. layout.tsx wraps child routes and persists across navigation, while loading.tsx and error.tsx handle waiting and failure.

Explained simply

In a Next.js app, you do not write a list of routes by hand. The folders inside the app directory are the routes. A folder called about with a page.tsx file inside it becomes the page at /about.

Some files have special names. page.tsx is what people see at that address. layout.tsx is a frame that wraps the page, such as a header and sidebar. loading.tsx is shown while the page is getting ready, and error.tsx is shown if something breaks.

Layouts are clever: when you move between pages that share a layout, the layout stays on screen and keeps its state. Only the inside part changes. So a sidebar's scroll position or a search box's text is not lost.

To move between pages, use the Link component instead of a plain a tag. Link loads the next page in the background and swaps it in without a full reload, so navigation feels instant.

Press Play on a diagram to walk through it one step at a time.

MapThe app directory maps to URLs
app/
  • layout.tsx
    • Root layout wraps every page
  • page.tsx
    • URL: /
  • blog/
    • layout.tsx
    • page.tsx is /blog
    • loading.tsx
  • blog/[slug]/
    • page.tsx is /blog/any-slug
    • error.tsx
MapOne app, three kinds of folders
app/
  • (marketing)/
    • layout.tsx with a big hero header
    • pricing/page.tsx is /pricing
  • (app)/
    • layout.tsx with sidebar
    • settings/page.tsx is /settings
  • docs/[...slug]/
    • page.tsx is /docs/a/b/c
  • _components/
    • Not routable, shared UI
  • not-found.tsx and global-error.tsx
    • App-wide 404 and crash screens

In depth

The special files and how they nest

Each route segment can have its own set of special files, and Next.js wraps them in a fixed order. From outside to inside: layout.tsx, then template.tsx, then an error boundary built from error.tsx, then a Suspense boundary built from loading.tsx, then a not-found boundary from not-found.tsx, and finally page.tsx. A child segment's layout sits inside its parent's page slot.

This order explains real behavior. An error in a page is caught by the error.tsx in the same folder, but an error in that folder's layout is caught by the parent's error.tsx, because the boundary sits inside the layout. template.tsx is like a layout that remounts on every navigation, useful for enter animations. The root layout must render the html and body tags.

LayersHow one segment's files wrap each other
  1. 1
    layout.tsx

    Persists across navigation

  2. 2
    template.tsx

    Optional; remounts on each navigation

  3. 3
    error.tsx boundary

    Catches errors below it

  4. 4
    loading.tsx boundary

    Suspense fallback while the page loads

  5. 5
    not-found.tsx boundary

    Shown when notFound() is called

  6. 6
    page.tsx

    The unique content for this URL

Dynamic segments in depth

A folder in square brackets matches any value: app/products/[id] serves /products/42. A catch-all [...slug] matches several parts, so app/docs/[...slug] serves /docs/a/b/c with slug as ["a", "b", "c"]. Double brackets [[...slug]] make it optional, so /docs matches too.

In current Next.js, params and searchParams are promises in pages and layouts: you write const { id } = await params. To build pages ahead of time, export generateStaticParams and return the list of params, for example every product id; Next.js renders those at build time. Call notFound() from next/navigation when the id does not exist, and the nearest not-found.tsx is shown with a 404 status.

  • [id]: one segment
  • [...slug]: one or more segments
  • [[...slug]]: zero or more segments
  • generateStaticParams pre-renders known values

Organizing without changing URLs

Some folder names do not become part of the URL. A route group is a folder in parentheses, such as (marketing) or (dashboard). It lets you group routes and give each group its own layout, so the marketing pages and the app pages can look completely different while URLs stay /pricing and /settings.

A private folder starts with an underscore, such as _components, and is never routable, which is a safe place for files that belong to a route but are not pages. Advanced patterns also exist: parallel routes use @folder slots to render two pages in one layout, and intercepting routes like (.)photo show a page as a modal while keeping a real URL. Learn the basics first; reach for these when a design needs them.

How navigation and prefetching work

The Link component renders a real a tag, so it works without JavaScript and for screen readers. Once the app is running, clicking it fetches only the data for the new route (the React Server Component payload), not a full HTML page, and React swaps in the changed segments while shared layouts stay.

In production, Next.js prefetches links when they scroll into view. For static routes it prefetches the whole route; for dynamic routes it prefetches down to the nearest loading.tsx, so the loading state can appear instantly. In client components, useRouter from next/navigation gives push, replace, back and refresh for navigation in code, such as after a form succeeds. usePathname and useSearchParams read the current URL. In server components and actions, use redirect() instead.

SequenceClicking a Link to /blog/hello
User
Browser (Next.js router)
Server
  1. 1prefetch when the link is visible
    Browser (Next.js router) to Server: prefetch when the link is visible
  2. 2route payload up to loading.tsx
    Server to Browser (Next.js router): route payload up to loading.tsx
  3. 3click
    User to Browser (Next.js router): click
  4. 4show loading state at once, layout stays
    Browser (Next.js router) to User: show loading state at once, layout stays
  5. 5fetch the rest of the page data
    Browser (Next.js router) to Server: fetch the rest of the page data
  6. 6stream the page content
    Server to Browser (Next.js router): stream the page content

Error handling that users can recover from

error.tsx must be a client component, so it starts with "use client". It receives the error and a reset function; calling reset tries to render the segment again, which helps with temporary failures. In production, the message of errors thrown in server components is hidden from the browser for security, and you get a digest id you can match with your server logs.

Errors in the root layout cannot be caught by app/error.tsx, because the boundary sits inside the layout. For that, add app/global-error.tsx, which replaces the whole document and must render its own html and body. For expected problems, such as a missing product or a failed validation, do not throw: return a message or call notFound(). Throwing is for unexpected failures.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Create routes with the app directory~50m
  2. 2
    Add nested layouts~50m
  3. 3
    Build dynamic route segments~50m
  4. 4
    Add loading.tsx and error.tsx~50m
  5. 5
    Navigate with Link and useRouter~50m

Key points

  • A folder becomes a route segment only when it contains page.tsx.
  • Layouts nest and keep their state when you navigate between child pages.
  • Square brackets like [slug] create dynamic segments read from params.
  • Use Link for navigation; it prefetches routes and avoids full page reloads.
  • useRouter from next/navigation handles programmatic navigation in client components.

Key terms

Tap a card to flip it. 0/6 known

Examples

tsx
// app/blog/[slug]/page.tsx
import Link from 'next/link';

type Props = { params: Promise<{ slug: string }> };

export default async function Post({ params }: Props) {
  const { slug } = await params;
  return (
    <article>
      <h1>{slug}</h1>
      <Link href="/blog">Back to blog</Link>
    </article>
  );
}

A dynamic route reading its slug and linking back.

A product page with static params and a 404

Step 1: generateStaticParams returns all known ids, so those pages are built ahead of time. Step 2: the page awaits params and loads the product. Step 3: if it is missing, notFound() shows the nearest not-found.tsx with a real 404 status, which search engines understand. Step 4: a loading.tsx next to the page covers slow loads.

tsx
// app/products/[id]/page.tsx
import { notFound } from "next/navigation";
import { getProduct, getProductIds } from "@/lib/products";

export async function generateStaticParams() {
  const ids = await getProductIds();
  return ids.map((id) => ({ id }));
}

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await getProduct(id);
  if (!product) notFound();
  return <h1>{product.name}</h1>;
}

An error screen with a retry button

Step 1: create error.tsx in the dashboard folder and mark it "use client". Step 2: log the error, for example to your monitoring tool, in an effect. Step 3: show a friendly message and a Try again button that calls reset. If the dashboard's data fetch fails, only the dashboard area shows this screen; the root layout with the navigation keeps working.

tsx
// app/dashboard/error.tsx
"use client";
import { useEffect } from "react";

export default function DashboardError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
  useEffect(() => {
    console.error(error);
  }, [error]);
  return (
    <div role="alert">
      <h2>Could not load your dashboard.</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

Quick reference

  • A folder is a URL segment; it is public only when it contains page.tsx
  • params and searchParams are promises: const { id } = await params
  • (group) folders organize routes and layouts without changing the URL
  • _folder is private and never becomes a route
  • error.tsx needs "use client"; root layout errors need global-error.tsx
  • notFound() shows not-found.tsx with a 404; redirect() works in server code
  • Link prefetches visible links in production; useRouter is for client-side code
  • generateStaticParams pre-renders dynamic routes at build time

Common mistakes

  • Using a plain anchor tag for internal links and losing client-side navigation.
  • Forgetting that error.tsx must be a client component.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which URL does app/(shop)/cart/page.tsx serve?

Question 2

2An error is thrown inside app/dashboard/layout.tsx. Which error.tsx catches it?

Question 3

3What does app/docs/[[...slug]]/page.tsx match that [...slug] does not?

Question 4

4In a client component, how do you send the user to /thanks after a successful save?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create the files for /, /about and /blog, where /blog has its own layout with a sidebar that does not appear on /about.

  2. Exercise 2medium

    Add a dynamic route /blog/[slug] that reads the slug, shows a loading state while it loads, and returns a 404 for unknown posts.

  3. Exercise 3hard

    Split an app into marketing pages (/, /pricing) with a hero layout and app pages (/dashboard, /settings) with a sidebar layout, each with its own error screen.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between the App Router and the Pages Router?
The App Router (app directory) is the current model, with server components, nested layouts and streaming. The Pages Router (pages directory) is the older model and is still supported, but new projects should use the App Router.
Should I use Link or an a tag in Next.js?
Use Link for links inside your app; it renders an a tag but adds prefetching and client-side navigation. Use a plain a tag for external sites.
Why are params a Promise in Next.js?
Since Next.js 15, params and searchParams are async so Next.js can start rendering before they are needed. Await them in server components, or use React's use() in client components.

Go deeper

ShareXLinkedInWhatsApp