Introduction to App Router
Next.js 14 introduces App Router - a revolutionary approach to routing and rendering in React applications. In this article you'll learn:
- What Server Components are
- How the new routing system works
- When to use Client Components
App Router Basics
App Router uses the app/ folder structure instead of the old pages/. Each folder represents a URL segment:
// app/blog/page.tsx
export default function BlogPage() {
return <h1>Blog</h1>
}
Server Components vs Client Components
Server Components (default):
- Rendered on the server
- Zero JavaScript sent to browser
- Direct database access
- Better SEO
Client Components ('use client'):
- Interactivity (useState, useEffect)
- Event handlers
- Browser APIs
Practical Example
Let's see how to create a simple page with API data:
// app/posts/page.tsx
async function getPosts() {
const res = await fetch('https://api.example.com/posts')
return res.json()
}
export default async function PostsPage() {
const posts = await getPosts()
return (
<div>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
</article>
))}
</div>
)
}
Routing and Navigation
Next.js App Router offers a new approach to navigation:
import Link from 'next/link'
export default function Navigation() {
return (
<nav>
<Link href="/blog">Blog</Link>
<Link href="/about">About</Link>
</nav>
)
}
Loading States and Error Handling
App Router makes it easy to manage loading states:
// app/blog/loading.tsx
export default function Loading() {
return <div>Loading...</div>
}
// app/blog/error.tsx
'use client'
export default function Error({ error, reset }) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
Summary
App Router is the future of Next.js. With Server Components you can build faster, more SEO-friendly applications.
Key takeaways:
- Use Server Components as default
- Client Components only when you need interactivity
- New folder structure is intuitive
- Loading and error states are easy to implement
Next Steps
Want to learn more about Next.js? Check out our other articles or contact us - we'll help you build a modern application!