Lesson 4 of 27Foundations
App Router Routing
Map an `app/` folder to URLs with pages, dynamic segments, catch-alls, route groups, typed routes and nested special files.
In a Next.js codebase the folder tree is the router. Every time you open a project, fix a 404, or add a page, you are reading app/ and translating folders into URLs. Get fluent at that translation and you will move through any Next.js app quickly, and answer the routing questions interviewers like to start with.
Folders are URL segments
The App Router lives in the app/ directory. Two rules do most of the work:
- Each folder is a URL segment.
app/blog/authors/maps to/blog/authors. - A folder only becomes a public page when it contains a
page.tsxfile (or aroute.tsfor an API endpoint, covered later). Other files in the folder are not reachable by URL.
- app/
- layout.tsxroot layout, wraps every page
- page.tsx/
- about/
- page.tsx/about
- blog/
- page.tsx/blog
- [slug]/
- page.tsx/blog/hello-world, /blog/any-slug
- opengraph-image.tsx
- _components/
- PostCard.tsxprivate: never a route
- docs/
- [[...slug]]/
- page.tsx/docs, /docs/a, /docs/a/b
- (marketing)/
- pricing/
- page.tsx/pricing (the group is not in the URL)
- api/
- health/
- route.tsGET /api/health
A page is just a default-exported React component:
export default function AboutPage() {
return <h1>About us</h1>;
}The root app/layout.tsx is required and must render <html> and <body>. You will meet layouts properly in the next lesson.
Here is the folder-to-URL translation as a function. Run it, then add your own paths.
Press Run (⌘ Enter) to see what happens.app/(shop)/products/page.tsx serve?Dynamic segments
Square brackets turn a folder into a parameter. The matched text arrives in the page's params prop.
| Folder | Matches | params |
|---|---|---|
blog/[slug] | /blog/hello | { slug: "hello" } |
shop/[...path] | /shop/a, /shop/a/b (not /shop) | { path: ["a", "b"] } |
docs/[[...path]] | /docs, /docs/a/b | {} or { path: ["a", "b"] } |
[...path] is a catch-all: one or more segments, as an array. [[...path]] is an optional catch-all: it also matches zero segments.
Since Next.js 15, params and searchParams are Promises. You await them in an async Server Component. Next.js also generates a global PageProps type from your folders, so the param names are checked for you:
import { notFound } from "next/navigation";
import { getPost } from "@/lib/posts";
export default async function PostPage(props: PageProps<"/blog/[slug]">) {
const { slug } = await props.params;
const post = await getPost(slug);
if (!post) notFound(); // renders the nearest not-found.tsx
return (
<article>
<h1>{post.title}</h1>
<p>{post.body}</p>
</article>
);
}Why Promises? Reading the URL is request-time work. Making it async lets Next.js prerender everything that does not depend on it and only wait where you actually await. In a Client Component you read the same values with useParams() and useSearchParams(), or by passing the Promise down and unwrapping it with React's use().
Match each URL to the folder that handles it (each has only one candidate).
Which route wins?
When more than one folder could match, the most specific wins: a static folder beats [slug], which beats [...rest], which beats [[...rest]]. So with both app/blog/new/page.tsx and app/blog/[slug]/page.tsx, the URL /blog/new goes to the static new page.
Search params
The query string (?sort=price&tag=a&tag=b) arrives as searchParams. A key that appears once is a string, a repeated key is an array:
export default async function SearchPage(props: PageProps<"/search">) {
const { q, tag } = await props.searchParams;
// q: string | string[] | undefined
// tag: ["a", "b"] for ?tag=a&tag=b
return <h1>Results for {String(q ?? "")}</h1>;
}Press Run (⌘ Enter) to see what happens.What does this print?
const p = new URLSearchParams("?page=2&tag=x&tag=y");
console.log(p.get("tag"));
console.log(p.getAll("tag").length);Typed routes and the PageProps helpers
You have already seen PageProps<"/blog/[slug]">. It is one of three global helpers Next.js generates from your folder tree:
| Helper | Used in | What it types |
|---|---|---|
PageProps<"/route"> | page.tsx | params and searchParams, both Promises |
LayoutProps<"/route"> | layout.tsx | params, children and any @slot props |
RouteContext<"/route"> | route.ts | the second argument of GET, POST and so on |
You never import them. They are written into a hidden folder (.next/types or .next/dev/types) whenever you run next dev, next build or next typegen. The string you pass must be a real route, so a typo like PageProps<"/blgo/[slug]"> is a type error, and renaming [slug] to [id] makes every params.slug read fail to compile instead of silently becoming undefined.
export default async function CategoryLayout(props: LayoutProps<"/shop/[category]">) {
const { category } = await props.params; // typed as string
return (
<section>
<h2>{category}</h2>
{props.children}
</section>
);
}The second half is typed links. Turn on typedRoutes: true in next.config.ts and the href of <Link>, plus router.push, replace and prefetch, only accept URLs that exist. Template literals such as `/blog/${slug}` are checked against your dynamic segments. A string built some other way, for example from a CMS, needs an explicit cast with as Route (imported as a type from next), which is a useful marker in code review: every cast is a link the compiler cannot vouch for.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
typedRoutes: true,
};
export default nextConfig;The catch is in CI. A plain tsc --noEmit runs before any route types exist, so it either fails on the missing globals or misses broken links. Generate them first:
npx next typegen && npx tsc --noEmitThat one line catches a whole class of "someone renamed a folder and three links now 404" bugs before review, and it is much cheaper than a full build.
tsc --noEmit on a fresh checkout and reports that PageProps is not defined. What is the fix?Organising without changing URLs
Two conventions let you keep code tidy without affecting routes:
- Route groups
(name): a folder in parentheses is skipped in the URL. Use them to group(marketing)pages apart from(app)pages, or to give a set of routes their own layout. - Private folders
_name: a folder starting with an underscore, and everything inside it, is excluded from routing.app/blog/_components/andapp/_lib/are safe places for code that belongs next to a route.
Any non-special file can live inside app/ safely, because only page and route files are public. Private folders make the intent obvious and avoid clashing with future file conventions.
Route groups and private folders in practice
The rules are simple. The value shows up in real apps, where different parts of the site need different chrome, and where teams want to find code next to the page that uses it.
- app/
- layout.tsxroot: <html>, <body>, fonts
- (marketing)/
- layout.tsxpublic header and footer
- page.tsx/
- pricing/
- page.tsx/pricing
- (app)/
- layout.tsxsidebar, user menu
- dashboard/
- (overview)/
- page.tsx/dashboard
- loading.tsxonly for /dashboard itself
- invoices/
- page.tsx/dashboard/invoices
- _components/
- InvoiceTable.tsx
- filters.ts
Three patterns are worth knowing by name:
- A layout for some routes, not all.
(marketing)/layout.tsxand(app)/layout.tsxsit at the same URL level but wrap different pages. Moving a page between groups changes its shell without changing its URL, so marketing can redesign their header without touching the product. - Scoping a special file.
dashboard/(overview)/loading.tsxonly covers/dashboard. If it sat directly indashboard/, it would also show while/dashboard/invoicesloads, which may not be what you want. The same trick scopes anerror.tsx. - Multiple root layouts. Delete
app/layout.tsxand give each group its own layout that renders<html>and<body>. This suits a product and an admin area with nothing in common. The cost: navigating between two root layouts is a full page load, not a client-side transition, and the home page/must live inside one of the groups.
Two groups must never produce the same URL. (marketing)/about/page.tsx and (app)/about/page.tsx both resolve to /about, and Next.js reports a conflict rather than picking one.
For colocation, the habit that scales is: a component or helper used by one route lives in that route's _components or _lib; once a second route needs it, it moves to a shared folder such as src/components. A file name alone would also keep it out of routing, but the underscore tells the next reader "nothing here is a URL" at a glance. If you ever need a URL segment that really starts with an underscore, name the folder %5Fname (the URL-encoded underscore).
Loading, error and not-found files
Each route folder can hold special files that wrap its page automatically:
loading.tsx: shown instantly while the page renders. Next.js wraps the page in a<Suspense>boundary with this as the fallback.error.tsx: catches errors thrown while rendering that segment and shows a fallback instead of crashing the whole app. It must be a Client Component.not-found.tsx: shown when the segment callsnotFound()or no route matches.
The layout is outermost. It stays mounted when you navigate between pages below it.
"use client"; // error boundaries run in the browser
export default function DashboardError({ error, retry }: { error: unknown; retry: () => void }) {
const message = error instanceof Error ? error.message : "Unknown error";
return (
<div role="alert">
<h2>Something went wrong</h2>
<p>{message}</p>
<button onClick={() => retry()}>Try again</button>
</div>
);
}retry() re-fetches and re-renders the segment. (Older code uses reset(), which re-renders without re-fetching.) For errors in the root layout itself there is app/global-error.tsx, which must render its own <html> and <body>.
app/dashboard/layout.tsx throws while rendering. app/dashboard/error.tsx exists. What happens?How special files nest across segments
The tree above is for one folder. A real URL passes through several folders, and each one repeats the same pattern inside its parent's. Once you can picture the full tree you can predict what the user sees when something throws or loads slowly.
Layouts nest from the outside in. Each child segment renders inside the boundaries of its parent.
Two rules fall out of this, and they explain most "why is my error page not showing?" questions:
- A boundary only catches what is below it. To catch a layout's error, put the boundary one folder up.
- The more nested the boundary, the more UI survives. An
error.tsxnext to each major section keeps navigation and headers usable when one widget breaks. A singleapp/error.tsxturns every failure into a whole-page failure.
Choosing where boundaries go, global-error.tsx, error digests in production and the 16.3 catchError helper are covered in Error Handling in Next.js. Designing loading boundaries and streaming are covered in Streaming, Loading UI and Instant Navigations.
Order the special files of one segment from outermost to innermost, as Next.js renders them.
- Tap the steps below in the right order.
template.tsx vs layout.tsx: what remounts
The Layouts and Navigation lesson shows the headline difference: layouts keep state, templates reset it. The detail that matters at work is which templates remount on a given navigation, because it decides whether a form clears or an animation replays.
Next.js gives each template a key built from the URL up to and including the segment directly below it. When that key changes, React throws away the template's subtree and mounts a fresh one. Three consequences:
- A template remounts only when the segment just below it changes, including a dynamic param like
[slug]. - Navigations deeper down do not remount a higher template.
- Search params are not part of the key. Going from
?page=1to?page=2remounts nothing.
Run this model of the rule against a root app/template.tsx and an app/blog/template.tsx:
Press Run (⌘ Enter) to see what happens.When should you reach for a template? Mostly for enter animations and per-page effects that must run on every visit, such as logging a page view from a Client Component. Use them sparingly. Everything inside a template is recreated on each matching navigation, including its DOM, so a template high in the tree throws away more work than you might expect. If you only need one input to reset, giving that component its own key is cheaper and more precise.
app/shop/template.tsx wraps a filter panel with local state. The user goes from /shop/shoes?color=red to /shop/shoes?color=blue. What happens to the panel?Debugging routing problems
Most routing bugs you will be asked to fix fall into a short list. Learn the symptoms and you can usually spot the cause from the file tree alone.
- A 404 for a page that "exists". The file is named
Page.tsxorindex.tsx, sits in a_privatefolder, or has no default export. Only a default-exportedpage.tsx(or.ts,.jsx,.js) counts. - "You cannot use different slug names for the same dynamic path". Two sibling folders such as
[id]and[slug]sit at the same level. Next.js cannot tell them apart, so pick one name and branch inside the page. - A page and an API endpoint fight over a URL. A folder cannot hold both
page.tsxandroute.ts, because both would answerGETat the same path. Move the endpoint underapi/or a sibling folder. - Two groups resolve to the same URL. Rename one or merge them.
- The wrong page wins. Remember the specificity order from earlier: a static folder beats
[slug], which beats catch-alls. A newblog/new/page.tsxsilently takes/blog/newaway from your[slug]page. - The error page never appears. The boundary is in the same folder as the layout that throws. Move it up one level.
When in doubt, run next build. Its route table lists every route it found and whether each is static or dynamic, which settles "does Next.js even see this page?" in seconds.
File path to URL
Write fileToRoute(path) that turns a file in the app/ folder into the URL pattern it serves, or null if it is not a route.
Rules:
- Only files named
pageorroute(any of.tsx .ts .jsx .js) create routes. Everything else returnsnull. - A folder starting with
_is private: the file is never a route. - Route groups like
(marketing)and slots like@modalare removed from the URL. - Dynamic folders like
[slug]stay as they are.
"app/page.tsx" → "/"
"app/(marketing)/about/page.tsx" → "/about"
"app/blog/[slug]/page.tsx" → "/blog/[slug]"
"app/blog/_components/Card.tsx" → nullBuild the App Router matcher
Write matchRoute(pathname, routes): find which route pattern handles a URL and extract its params. Return { route, params } or null.
Segment types in a pattern:
about: static, must equal the URL segment[slug]: one segment,params.slug = "hello"[...rest]: one or more segments,params.rest = ["a", "b"][[...opt]]: zero or more segments; when zero, leaveoptout ofparams(group): ignored, it is not part of the URL
If several patterns match, pick the most specific: compare segment by segment from the left, where static beats [param], which beats [...rest], which beats [[...opt]]. Ignore empty segments (so /blog/ equals /blog).
matchRoute("/blog/hello", ["/blog", "/blog/[slug]"])
→ { route: "/blog/[slug]", params: { slug: "hello" } }
matchRoute("/blog/new", ["/blog/[slug]", "/blog/new"])
→ { route: "/blog/new", params: {} }- route segment
- One part of a URL path, defined by one folder in
app/. - dynamic segment
- A folder in square brackets like
[slug]that matches any value and passes it inparams. - catch-all segment
[...slug]matches one or more segments;[[...slug]]also matches zero. The value is an array.- route group
- A folder in parentheses like
(marketing)that organises routes without appearing in the URL. - private folder
- A folder starting with
_whose files are never routable. Good for colocated components and helpers. - loading.tsx
- A special file that becomes the Suspense fallback for its route segment.
- PageProps / LayoutProps / RouteContext
- Global types Next.js generates from
app/soparams,searchParamsand slots are checked against real routes. - typedRoutes
- A
next.config.tsoption that makes<Link href>and router methods accept only URLs that exist. - next typegen
- A CLI command that writes the route types without a full build, so
tsccan run in CI. - template.tsx
- A wrapper keyed by the segment below it, so its subtree remounts when that segment changes.