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:
- Create the
app/Directory: At your project root, create anapp/folder. This will replace the traditionalpages/directory for routing purposes. - Define Route Segments: Each subfolder within
app/represents a route segment. For example,app/blog/corresponds to the/blogpath. - 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.tsxabout/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.tsxlayout.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
| File | Purpose |
|---|---|
page.tsx | Defines the unique UI for a route; makes it accessible at its path. |
layout.tsx | Wraps child routes in shared UI; persists state across navigation. |
loading.tsx | Shows a loading UI with React Suspense during data fetching or lazy loading. |
error.tsx | Acts as an error boundary for a route segment. |
not-found.tsx | Renders UI for 404 Not Found responses. |
template.tsx | Like layout, but re-renders on navigation for non-persistent layouts. |
default.tsx | Fallback 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]]/→/shopor/shop/*
Example: Dynamic Route
app/
└── blog/
└── [slug]/
└── page.tsxblog/[slug]/page.tsx
export default function BlogPost({ params }) {
return <h1>Blog Post: {params.slug}</h1>;
}Best Practices
- Use Layouts for Shared UI: Implement
layout.tsxat appropriate folder levels to share navigation, sidebars, or authentication guards. - Implement Loading and Error States: Use
loading.tsxanderror.tsxin 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.tsxwhen 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.
More Skills You Might Like
Explore similar skills to enhance your workflow
Team Composition Analysis
Design optimal team structures, hiring plans, compensation strategies, and equity allocation for early-stage startups from pre-seed through Series A
Flux Image
Flux Image automation for generating and processing high-quality creative visual content
Pptx
Presentation creation, editing, and analysis. When Claude needs to work with presentations (.pptx files) for: (1) Creating new presentations, (2) Modi
Gemini Live API Dev
Use this skill when building real-time, bidirectional streaming applications with the Gemini Live API. Covers WebSocket-based audio/video/text
Saga Orchestration
Patterns for managing distributed transactions and long-running business processes without two-phase commit
Apache Airflow DAG Patterns
Production-ready patterns for Apache Airflow including DAG design, operators, sensors, testing, and deployment strategies