Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 02 / Stage 1

File-based routing

Goal: Turn folders into URLs — nested routes, dynamic segments ([id]), catch-all segments ([...slug]), route groups, colocation, and the programmatic notFound() — by building a small storefront route tree inside this course's harness, and know exactly how this differs from the client-side router (React Router) the prerequisite course taught. Time: ~5 h · Level: 🟢 finished Part 1, new to Next.js routing

What you will learn

  • How a folder becomes a URL, and why there is no central routes file to read
  • How this contrasts with the client-side router (React Router) the prerequisite course taught
  • The full list of special filenames the App Router recognizes, and which ones this part covers versus later parts
  • Nested routes: folders nest, URLs nest the same way
  • Dynamic segments ([id]) and why params is a Promise you must await
  • Catch-all segments ([...slug]) versus the optional form ([[...slug]])
  • Route groups ((group)) to organize files on disk without changing a single URL
  • Colocation: why a data file sitting next to a page.tsx doesn't become a route, and the _folder private-folder convention
  • notFound(): throwing your way to a 404 from inside a Server Component

Topics in this part

Practice

Every exercise adds files under harness/app/store/ (or a sibling folder), runs a real command against them, and then removes what it added, restoring the harness to the exact route tree Part 2's README ends on — /store, /store/about, /store/contact, /store/products, /store/products/[id], /store/search/[...terms] — the same tree Part 3 starts from. Copy the exact commands you ran and their real output into your own notes; do not type output from memory.


Exercise 1: A new nested route

Scenario: Apna Bazaar wants a seasonal offers page. What to do: Create app/store/offers/page.tsx with an <h1>Diwali Offers</h1> and one line of body text. Run next build and confirm /store/offers appears in the route table as ○ (Static). Then delete the folder and rebuild to confirm you're back to the six routes above.

Sample output (run for real against this course's harness):

$ npm run build
...
Route (app)
┌ ○ /
├ ○ /_not-found
├ ○ /store
├ ○ /store/about
├ ○ /store/contact
├ ○ /store/offers
├ ○ /store/products
├   /store/products/[id]
│ ├ ◐ /store/products/[id]
│ ├ ○ /store/products/p1
│ ├ ○ /store/products/p2
│ └ ○ /store/products/p3
└   /store/search/[...terms]
  ├ ◐ /store/search/[...terms]
  ├ ○ /store/search/silk
  └ ○ /store/search/pottery

💡 Hint: No import, no registration anywhere else — the folder and its page.tsx are the entire change. This is section 3's point made with your own hands.


Exercise 2: Prove a colocated file isn't a route

Scenario: You want to add a second data file next to lib/products.ts — say, a list of shipping zones — without worrying it will leak out as a public URL. What to do: Create app/store/lib/shipping.ts exporting a small array (city, days). Run next build — it should not appear anywhere in the route table. Then confirm with a running next dev that /store/lib/shipping 404s.

Sample output (run for real, against the general pattern — shipping.ts behaves exactly like the existing products.ts in the same folder):

$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:PORT/store/lib
404

💡 Hint: This is the same proof the README gives for lib/products.ts in section 7 — no page.tsx in that folder means nothing is reachable there, no matter how many plain .ts files you add.


Exercise 3: Your own dynamic segment, with notFound()

Scenario: Apna Bazaar wants a page per city it ships from. What to do: Create app/store/cities/[city]/page.tsx. Inside, keep a small Record<string, string[]> of known cities (jaipur, varanasi, chennai) mapped to the products made there, add generateStaticParams returning those three, await params to read city, and call notFound() from next/navigation when the city isn't in the record.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/store/cities/jaipur | grep -o '<main[^>]*>.*</main>'
<main><h1>Products from <!-- -->jaipur</h1><ul><li>Jaipur Blue Pottery Vase</li></ul></main>
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:PORT/store/cities/mumbai
404

Delete app/store/cities/ afterward — it is not part of this part's canonical harness state. 💡 Hint: Without generateStaticParams, this fails to build for exactly the reason section 4 shows for /store/products/[id] — cacheComponents: true refuses to prerender a dynamic route whose params it can't account for.


Exercise 4: A catch-all with breadcrumbs

Scenario: A "browse by category path" page: /store/browse/clothing, /store/browse/clothing/sarees, /store/browse/clothing/sarees/silk should all work, each showing the path as breadcrumbs. What to do: Create app/store/browse/[...path]/page.tsx. Add generateStaticParams returning at least { path: ["clothing"] }, await params, and render path.join(" / ").

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/store/browse/clothing/sarees/silk | grep -o '<main[^>]*>.*</main>'
<main><h1>Browse: <!-- -->clothing / sarees / silk</h1></main>

Delete app/store/browse/ afterward. 💡 Hint: This is the exact shape of section 5's [...terms] search route, reused for a different purpose — catch-all segments aren't only for search boxes.


Exercise 5: Trigger the route-group conflict on purpose

Scenario: Section 6 states that two route groups resolving to the same URL is a build error. Reproduce it with your own hands instead of taking the README's word for it. What to do: Create a second group, app/store/(admin)/about/page.tsx (any content), alongside the existing app/store/(info)/about/page.tsx. Run next build and copy the real error. Then delete the (admin) group and confirm the build is green again.

Sample output (run for real against this course's harness):

$ npm run build
...
> Build error occurred
Error: Turbopack build failed with 1 error:
./app/store/(info)
Error: You cannot have two parallel pages that resolve to the same path. Please check /store/(admin)/about and /store/(info).

💡 Hint: Both groups' names are invisible to the URL — that is exactly why they collide. Renaming one group doesn't fix anything; only changing the final path segment (about itself) would.


Exercise 6: A private folder beats a real page.tsx

Scenario: You're drafting a page you don't want live yet, and you want to be sure it can't accidentally go public even though it has a perfectly valid page.tsx. What to do: Create app/store/_draft/page.tsx with a normal, working component. Run next build and confirm the route table has no /store/_draft entry anywhere, even though the file compiles cleanly. Then confirm with next dev that the URL 404s.

Sample output (run for real against this course's harness):

$ npm run build
...
Route (app)
┌ ○ /
├ ○ /_not-found
├ ○ /store
├ ○ /store/about
├ ○ /store/contact
├ ○ /store/products
├   /store/products/[id]
│ ├ ◐ /store/products/[id]
│ ├ ○ /store/products/p1
│ ├ ○ /store/products/p2
│ └ ○ /store/products/p3
└   /store/search/[...terms]
  ├ ◐ /store/search/[...terms]
  ├ ○ /store/search/silk
  └ ○ /store/search/pottery
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:PORT/store/_draft
404

Delete app/store/_draft/ afterward. 💡 Hint: This is a stronger claim than Exercise 2's. lib/products.ts isn't a route because it has no page.tsx. _draft/page.tsx does have one, and is still not a route — the underscore itself is what opts it out, overriding the file that would otherwise make it public.


Exercise 7: Watch the generated route types change

Scenario: Section 9 read AppRoutes once, after the fact. Watch it change live as you add a route. What to do:

  1. grep "^type AppRoutes" harness/.next/types/routes.d.ts and copy the line.
  2. Add any new route (Exercise 1's app/store/offers/page.tsx works), run next build.
  3. Run the same grep again and compare.
  4. Remove the route, rebuild, and confirm the type reverts.

Sample output (run for real against this course's harness):

$ grep "^type AppRoutes" harness/.next/types/routes.d.ts
type AppRoutes = "/" | "/store" | "/store/about" | "/store/contact" | "/store/products" | "/store/products/[id]" | "/store/search/[...terms]"

$ mkdir -p app/store/offers && printf 'export default function OffersPage() {\n  return <main>Diwali Offers</main>;\n}\n' > app/store/offers/page.tsx
$ npm run build
...
$ grep "^type AppRoutes" harness/.next/types/routes.d.ts
type AppRoutes = "/" | "/store" | "/store/about" | "/store/contact" | "/store/offers" | "/store/products" | "/store/products/[id]" | "/store/search/[...terms]"

💡 Hint: routes.d.ts lists bracket syntax literally (/store/products/[id]) and never shows a route-group name — both facts section 9 already pointed at, now watched changing in real time rather than read once. If a stray type error later mentions a route you already deleted, rm -rf harness/.next and rebuild — the Common Mistakes table in the README explains why.

Show the solutions for Part 2 (7 files)

solutions/ex01.tsx

// Solution to Exercise 1. Drop in as harness/app/store/offers/page.tsx,
// then: npm run build (and check the route table for /store/offers).
// Delete the app/store/offers/ folder afterward — this is not part of
// the harness's canonical Part 2 state.
export default function OffersPage() {
  return (
    <main>
      <h1>Diwali Offers</h1>
      <p>Flat 10% off on all pottery this week.</p>
    </main>
  );
}

solutions/ex02.ts

// Solution to Exercise 2. Drop in as harness/app/store/lib/shipping.ts,
// right next to the existing lib/products.ts. No page.tsx lives in
// app/store/lib/, so neither file is a route, however many you add.
// Delete it afterward — it is not part of the harness's canonical state.
export type ShippingZone = {
  city: string;
  days: number;
};

export const shippingZones: ShippingZone[] = [
  { city: "Jaipur", days: 2 },
  { city: "Varanasi", days: 4 },
  { city: "Chennai", days: 5 },
];

solutions/ex03.tsx

// Solution to Exercise 3. Drop in as harness/app/store/cities/[city]/page.tsx,
// then: npm run build (needs generateStaticParams, same reason as
// /store/products/[id] in the README's section 4), then curl
// /store/cities/jaipur (200) and /store/cities/mumbai (404). Delete
// app/store/cities/ afterward — it is not part of the harness's
// canonical Part 2 state.
import { notFound } from "next/navigation";

const cityStock: Record<string, string[]> = {
  jaipur: ["Jaipur Blue Pottery Vase"],
  varanasi: ["Banarasi Silk Saree"],
  chennai: ["Chennai Filter Coffee Set"],
};

export function generateStaticParams() {
  return Object.keys(cityStock).map((city) => ({ city }));
}

export default async function CityPage({
  params,
}: {
  params: Promise<{ city: string }>;
}) {
  const { city } = await params;
  const items = cityStock[city.toLowerCase()];

  if (!items) {
    notFound();
  }

  return (
    <main>
      <h1>Products from {city}</h1>
      <ul>
        {items.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </main>
  );
}

solutions/ex04.tsx

// Solution to Exercise 4. Drop in as
// harness/app/store/browse/[...path]/page.tsx, then: npm run build
// (needs generateStaticParams, same reason as /store/search/[...terms]
// in the README's section 5), then curl
// /store/browse/clothing/sarees/silk. Delete app/store/browse/
// afterward — it is not part of the harness's canonical Part 2 state.
export function generateStaticParams() {
  return [{ path: ["clothing"] }];
}

export default async function BrowsePage({
  params,
}: {
  params: Promise<{ path: string[] }>;
}) {
  const { path } = await params;
  return (
    <main>
      <h1>Browse: {path.join(" / ")}</h1>
    </main>
  );
}

solutions/ex05.md

# Solution to Exercise 5: trigger the route-group conflict on purpose

Add a second route group next to the existing `harness/app/store/(info)/about/page.tsx`:

```tsx
// harness/app/store/(admin)/about/page.tsx
export default function AdminAboutPage() {
  return <main>Admin About</main>;
}
```

Both files resolve to the same URL, `/store/about` — the `(info)` and `(admin)` folder names are both invisible to the router. Real error, run against this course's harness:
```text
$ npm run build
...
> Build error occurred
Error: Turbopack build failed with 1 error:
./app/store/(info)
Error: You cannot have two parallel pages that resolve to the same path. Please check /store/(admin)/about and /store/(info).
```

Delete `harness/app/store/(admin)/` and rebuild to confirm the build is green again:
```text
$ npm run build
...
Route (app)
┌ ○ /
├ ○ /_not-found
├ ○ /store
├ ○ /store/about
├ ○ /store/contact
├ ○ /store/products
├   /store/products/[id]
│ ├ ◐ /store/products/[id]
│ ├ ○ /store/products/p1
│ ├ ○ /store/products/p2
│ └ ○ /store/products/p3
└   /store/search/[...terms]
  ├ ◐ /store/search/[...terms]
  ├ ○ /store/search/silk
  └ ○ /store/search/pottery
```

The fix is never to rename a group — groups are invisible to the URL by design. The only real fix is to change the colliding path segment itself (here, `about`) in one of the two routes.

solutions/ex06.tsx

// Solution to Exercise 6. Drop in as harness/app/store/_draft/page.tsx —
// a fully valid page.tsx, inside a folder prefixed with an underscore.
// The underscore opts the folder out of routing even though this file
// would otherwise make /store/_draft public. Confirmed by running
// `npm run build` (no /store/_draft line anywhere in the route table)
// and, with `next dev` running, curling the URL (404). Delete
// app/store/_draft/ afterward — it is not part of the harness's
// canonical Part 2 state.
export default function DraftPage() {
  return <main>Draft, not live yet</main>;
}

solutions/ex07.md

# Solution to Exercise 7: watch the generated route types change

Before adding anything, read the current type — run for real against this course's harness:
```text
$ grep "^type AppRoutes" harness/.next/types/routes.d.ts
type AppRoutes = "/" | "/store" | "/store/about" | "/store/contact" | "/store/products" | "/store/products/[id]" | "/store/search/[...terms]"
```

Add Exercise 1's route and rebuild:
```tsx
// harness/app/store/offers/page.tsx
export default function OffersPage() {
  return <main>Diwali Offers</main>;
}
```
```text
$ npm run build
```

Read the type again — `/store/offers` is now in the union, inserted alphabetically:
```text
$ grep "^type AppRoutes" harness/.next/types/routes.d.ts
type AppRoutes = "/" | "/store" | "/store/about" | "/store/contact" | "/store/offers" | "/store/products" | "/store/products/[id]" | "/store/search/[...terms]"
```

Delete `harness/app/store/offers/` and rebuild — the type reverts to the first line above. Two facts worth noticing in both lines: `/store/about` and `/store/contact` never show the `(info)` group they actually live inside, and `/store/products/[id]` / `/store/search/[...terms]` are listed with their literal bracket syntax, not an example value — `routes.d.ts` is reporting the folder tree exactly as the router resolved it, not a separate configuration.

If a later type error ever references a route you already deleted (a stale `app/dev/types/validator.ts` entry), the fix is `rm -rf harness/.next` followed by a clean rebuild — the generated-types cache, not your source code, is out of date.

Common mistakes

Mistake Why it is wrong Fix
Looking for a central routes file The App Router has none — reproduced throughout this part, the folder tree under app/ is the only configuration Read the folder structure, not a routes array
Reading params.id directly, no await params is a Promise in Next.js 16; reading it synchronously is a type error against this course's generated types const { id } = await params;
Forgetting generateStaticParams on a dynamic/catch-all route With cacheComponents: true (on by default, Part 1), the build fails outright — reproduced for real in section 4 Add generateStaticParams for known values, or wait for Stage 2/3's <Suspense>/"use cache" patterns
Expecting a required catch-all to match its own parent path /store/search 404s under [...terms] — proven in section 5 Use the optional form, [[...terms]], if the bare path should also match
Two route groups resolving to the same URL Real build error, reproduced in section 6: "You cannot have two parallel pages that resolve to the same path" Give the colliding routes different final path segments, or merge the groups
Assuming any file under app/ becomes a route Only a folder with its own page.tsx (or route.ts) is reachable — lib/products.ts proves the opposite in section 7 Colocate freely; add _folder only when you want to opt out even more explicitly
Deleting a route folder and not re-running a clean build Stale entries in .next/dev/types/validator.ts can reference a route that no longer exists, surfacing as a confusing type error for a file you didn't touch rm -rf harness/.next and rebuild when a type error mentions a route you just deleted

Quick recap

  • A route exists because a folder inside app/ contains a page.tsx — there is no routes file to register it in, unlike the client-side router from the prerequisite course.
  • Folders nest, URLs nest the same way: app/store/products/page.tsx is /store/products.
  • [id] captures one segment, [...slug] captures one or more, [[...slug]] additionally matches the bare parent path; params is always a Promise.
  • cacheComponents: true means a dynamic or catch-all route needs generateStaticParams (or a Stage 2/3 technique not yet taught) to build at all.
  • (group) organizes files on disk without touching the URL, but two groups resolving to the same path is a build error, not a silent pick-one.
  • Any file under app/ is safely colocated unless it is itself a page.tsx/route.ts; _folder opts a folder out of routing explicitly, even past a page.tsx inside it.
  • notFound() throws NEXT_HTTP_ERROR_FALLBACK;404 and hands rendering to the nearest not-found UI — Next.js's own default 404 page, until Part 3 adds a custom one.

Checklist

  • I can explain why the App Router has no central routes file, contrasting it with React Router.
  • I built a nested route two folders deep and watched the URL nest the same way.
  • I built a dynamic segment, awaited params, and added generateStaticParams to keep the build green.
  • I built a required catch-all segment and proved it does not match its own parent path.
  • I built a route group and proved its name never appears in the URL, then triggered the real "two routes, one path" build error on purpose.
  • I colocated a non-route file inside app/ and proved its folder 404s, then did the same with an underscore-prefixed private folder that does contain a page.tsx.
  • I called notFound() from a Server Component and confirmed the response is a real 404.

Search the guide