App Router

This skill should be used when the user asks to "create a Next.js route", "add a page", "set up layouts", "implement loading states", "add error bound

What Is App Router?

The App Router is a pivotal component of Next.js, the popular React framework for building web applications. Introduced as a modern replacement for the traditional pages/ directory, the App Router leverages a file-system based routing approach via the app/ directory. It is built on top of React Server Components, offering developers a powerful and flexible system for defining routes, layouts, data loading strategies, error handling, and more. By organizing application structure around folders and special files, the App Router allows for highly modular and maintainable code, while supporting advanced features such as nested layouts, loading states, error boundaries, and dynamic routing patterns.

Why Use App Router?

Using the App Router provides several benefits over older Next.js routing paradigms:

  • Enhanced Modularity: The file-based convention naturally segments your application into manageable, reusable components.
  • Server and Client Component Support: Seamless integration of React Server Components allows developers to optimize rendering and data fetching.
  • Nested Layouts: Create complex UI structures with persistent layouts that survive route changes, improving the user experience and developer productivity.
  • Fine-grained Loading and Error States: Implement loading and error boundaries at any route segment, resulting in more resilient and responsive interfaces.
  • Dynamic and Catch-all Routing: Effortlessly support dynamic routes and catch-all patterns with clear, convention-based folder naming.

Ultimately, the App Router simplifies complex routing scenarios, reduces boilerplate, and aligns closely with modern React patterns.

How to Get Started

Getting started with the App Router involves re-structuring your Next.js project to use the app/ directory, and organizing your routes and UI logic according to convention. Here’s a step-by-step guide:

  1. Create the app/ Directory: At your project root, create an app/ folder. This will replace the traditional pages/ directory for routing purposes.
  2. Define Route Segments: Each subfolder within app/ represents a route segment. For example, app/blog/ corresponds to the /blog path.
  3. Add Special Files: Inside each route segment folder, use special files to control the UI and behavior for that route.

Example: Creating a Basic Route

app/
  └── about/
      └── page.tsx

about/page.tsx

export default function AboutPage() {
  return <h1>About Us</h1>;
}

This setup exposes the /about route with a simple page component.

Example: Adding a Layout

To share layout across multiple pages:

app/
  └── layout.tsx
  └── page.tsx
  └── blog/
      └── page.tsx

layout.tsx

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <nav>/* Navigation */</nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

Key Features

The App Router revolves around key file and folder conventions that define how your application behaves:

Core File Conventions

FilePurpose
page.tsxDefines the unique UI for a route; makes it accessible at its path.
layout.tsxWraps child routes in shared UI; persists state across navigation.
loading.tsxShows a loading UI with React Suspense during data fetching or lazy loading.
error.tsxActs as an error boundary for a route segment.
not-found.tsxRenders UI for 404 Not Found responses.
template.tsxLike layout, but re-renders on navigation for non-persistent layouts.
default.tsxFallback component for parallel routes.

Folder Conventions

  • Static Segment: app/blog//blog
  • Dynamic Segment: app/blog/[slug]//blog/:slug
  • Catch-all Segment: app/docs/[...slug]//docs/*
  • Optional Catch-all: app/shop/[[...slug]]//shop or /shop/*

Example: Dynamic Route

app/
  └── blog/
      └── [slug]/
          └── page.tsx

blog/[slug]/page.tsx

export default function BlogPost({ params }) {
  return <h1>Blog Post: {params.slug}</h1>;
}

Best Practices

  • Use Layouts for Shared UI: Implement layout.tsx at appropriate folder levels to share navigation, sidebars, or authentication guards.
  • Implement Loading and Error States: Use loading.tsx and error.tsx in route segments that fetch data or might fail, to enhance user experience.
  • Organize Complex UIs with Nested Routes: Break large pages into nested routes, allowing for modular development and code splitting.
  • Name Dynamic Segments Clearly: Use descriptive names for dynamic segments (e.g., [productId]) to improve code readability.
  • Leverage Templates for Non-Persistent Layouts: Use template.tsx when you want layouts to reset state on navigation, such as in wizards or multi-step forms.

Important Notes

  • SSR and Client Components: By default, files in app/ are React Server Components. To use client-side features like hooks or state, add "use client" at the top of your file.
  • File Naming is Critical: The App Router is sensitive to file and folder names; misspelled or misplaced files will result in missing routes or unexpected behavior.
  • Migration from Pages Router: Migrating from the traditional pages-based router requires moving files into the app/ directory and adapting to new conventions.
  • Parallel and Intercepting Routes: Advanced routing patterns like parallel routes and intercepting routes are also supported, but require a good understanding of the folder and file structure.
  • Documentation: Always refer to the official Next.js documentation and verify plugin or skill-specific enhancements for the latest best practices and updates.