App Router Deep Dive
⏱ Estimated reading time: 3 min
The App Router is the modern routing system in Next.js (v13+), designed to replace the older Pages Router. It provides file-based routing, nested layouts, server components, and advanced data fetching. Understanding it deeply helps build scalable, maintainable, and SEO-friendly applications.
1. App Router Basics
-
Located in the
app/directory. -
Each folder represents a route, and each
page.jsfile represents the UI for that route. -
Supports nested routes, dynamic routes, and layouts.
-
Fully compatible with React Server Components and client components.
Example Structure
2. Layouts
Root Layout
-
Must include
<html>and<body>tags. -
Wraps all pages in the app.
Nested Layout
-
Applies only to pages inside a folder.
3. Pages and Routing
-
Static routes:
app/about/page.js→/about -
Dynamic routes:
[slug]/page.js→/blog/my-post -
Catch-all routes:
[...slug]/page.js→/docs/react/hooks -
Optional catch-all:
[[...slug]]/page.js→/docsor/docs/react
4. Data Fetching in App Router
Supports server-side fetching in pages and layouts:
-
Server Components: Default; fetch data on server.
-
Static Rendering: Default for fetch with no cache options.
-
Dynamic Rendering:
cache: 'no-store' -
Incremental Static Regeneration (ISR):
next: { revalidate: 60 }
Example:
5. Server vs Client Components
-
Server Components (default in App Router):
-
Rendered on the server
-
Can fetch data directly
-
Do not include JS in client bundle
-
-
Client Components:
-
Marked with
'use client' -
Needed for interactivity, hooks, and browser APIs
-
6. Error Handling
-
Use
error.jsin any folder to catch route-specific errors. -
not-found.jsfor 404 pages.
7. Loading and Suspense
-
Use
loading.jsfor skeleton UI while page or layout loads. -
Supports React Suspense for streaming UI.
8. API Routes in App Router
-
Located under
app/api/.../route.js -
Support HTTP methods like GET, POST, PUT, DELETE
9. Advantages Over Pages Router
| Feature | Pages Router | App Router |
|---|---|---|
| Layouts | Limited | Nested layouts |
| Data fetching | getServerSideProps / getStaticProps | Direct fetch() in server components |
| Server components | ❌ | ✅ (default) |
| Streaming UI | ❌ | ✅ with Suspense |
| File-based API | pages/api | app/api/route.js |
10. Best Practices
-
Use nested layouts for shared UI
-
Prefer server components for data fetching
-
Use client components only when needed
-
Organize routes cleanly with folders
-
Use
error.jsandloading.jsfor better UX -
Leverage dynamic and catch-all routes for flexible URLs
Conclusion
The App Router is a powerful upgrade in Next.js that combines routing, layouts, data fetching, and server-side rendering seamlessly. Mastering it allows you to build modern, scalable, and SEO-friendly web applications efficiently.
Register Now
Share this Post
← Back to Tutorials