Course outline · 0% complete

0/29 lessons0%

Course overview →

Folders become URLs

lesson 2-2 · ~12 min · 5/29

The routing rule

One rule covers almost everything:

Each folder under app/ is one URL segment, and the page.js inside it is the UI for that URL.

So:

  • app/page.js/
  • app/about/page.js/about
  • app/blog/drafts/page.js/blog/drafts

Nest folders and you nest URL segments, exactly like directories on disk. Compare this with Backend with Node.js, where you wrote app.get("/blog/drafts", handler) by hand. Next.js derives the same route table from your file system, which means the route list can never drift out of sync with the code.

Worked example: sketch a site before you code it

This mapping is how working engineers plan a site: write the URL list first, then the folders fall out mechanically. Say a bakery wants four pages:

URL the customer typesFile you create
/app/page.js
/menuapp/menu/page.js
/menu/cakesapp/menu/cakes/page.js
/contactapp/contact/page.js

Two details worth noticing:

  • /menu and /menu/cakes are separate pages: nesting the cakes folder inside menu does not remove the need for menu/page.js if /menu itself should render.
  • Folder names become public URL segments, so name them the way users should read them (menu, not MenuStuff).
app/page.jsabout/page.jsblog/drafts/page.js//about/blog/draftsURLFiles
File-based routing: each folder under app/ is a URL segment, and page.js marks the UI rendered there.

Quiz

Which file makes the URL /shop/cart work?

Code exercise · javascript

Practice the mapping in pure JavaScript (this logic is runnable, unlike JSX). Write routeFromPath(filePath): it receives a path like "app/blog/drafts/page.js", strips the leading "app" and the trailing "/page.js", and returns the URL. The homepage "app/page.js" must return "/". Use the string methods you know from Advanced JavaScript.

Quiz

The bakery adds a seasonal page at /menu/cakes/holiday. Which file makes that URL render?