App Router File-Based Routing

▲ Next.js Lesson 2 Beginner

Next.js features a file-system based router built on the App Router model, where folder structures directly map URL routes and layouts.

1 Core Routing Components

In Next.js, routes are defined by folder hierarchies, using specific reserved files to structure views:

  • page.js / page.tsx: Defines the unique UI rendered for a specific route. A folder must contain a page.js file to be publicly accessible.
  • layout.js / layout.tsx: Defines shared layouts across subroutes (e.g. Navbars, Sidebars), preserving state and avoiding re-renders on transitions.
  • Dynamic Routes ([id]): Folders wrapped in square brackets define dynamic parameters (e.g. app/blog/[slug]/page.js maps to /blog/first-post).
2 Defining Layouts and Pages in Code

Let's check how layout templates wrap pages dynamically:

React — app/layout.js
// Root layout wraps all pages
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <header>
          <nav>Shared Navigation Header</nav>
        </header>
        <main>{{ children }}</main>
        <footer>Shared Footer</footer>
      </body>
    </html>
  );
}

The content is projected into the root layout inside the children parameter dynamically.

3 Code Challenge
Challenge: Create a folder hierarchy inside your project called app/dashboard/settings/, add a page.js file returning a heading, and verify you can access it in the browser at /dashboard/settings.