Module 2: Routing & Layouts

Mastering the File-System Based Router in the App Directory

Special File Conventions

The App Router uses specific file names to define UI and behavior.

File Purpose Component Type
page.js The UI for a route. Makes the path accessible. Server (default)
layout.js Shared UI for a segment and its children. Preserves state on navigation. Server (default)
template.js Similar to layout, but creates a new instance on navigation. Server (default)
loading.js Loading UI (React Suspense boundary). Client or Server
not-found.js UI for 404 errors. Client
error.js Error UI (React Error Boundary). Must be a Client Component. Client

Dynamic Routing

Handle dynamic segments using square brackets.

1. Basic Dynamic Segment

app/blog/[slug]/page.js matches /blog/hello-world

// app/blog/[slug]/page.js
export default function BlogPost({ params }) {
  return 
Post ID: {params.slug}
}

2. Catch-all Segments

app/docs/[...slug]/page.js matches /docs/a, /docs/a/b

// params.slug will be an array: ['a', 'b']

3. Optional Catch-all

app/docs/[[...slug]]/page.js also matches /docs (no params).

Advanced Patterns

Route Groups (folder)

Organize routes without affecting the URL path. Useful for opting out of a layout.

  • app/(marketing)/about/page.js -> /about
  • app/(shop)/cart/page.js -> /cart

Parallel Routes @folder

Render multiple pages in the same layout simultaneously (e.g., Dashboards).

// app/layout.js
export default function Layout({ children, team, analytics }) {
  return (
    <>
      {children}
      {team}      {/* mapped to app/@team/page.js */}
      {analytics} {/* mapped to app/@analytics/page.js */}
    
  )
}