A comprehensive guide to building modern web applications with Next.js 14 App Router
Next.js 14 introduces the App Router, a new paradigm for building React applications. In this guide, we'll explore the key features and benefits of the App Router.
The App Router is built on top of React Server Components and brings several improvements:
Here's a typical App Router project structure:
app/
├── layout.tsx # Root layout
├── page.tsx # Home page
├── about/
│ └── page.tsx # About page
└── blog/
├── page.tsx # Blog listing
└── [slug]/
└── page.tsx # Blog post
Creating a page is as simple as adding a page.tsx
file:
// app/about/page.tsx
export default function AboutPage() {
return (
<div>
<h1>About Me</h1>
<p>Welcome to my about page!</p>
</div>
);
}
Layouts allow you to share UI across multiple pages:
// app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<nav>{/* Navigation */}</nav>
<main>{children}</main>
<footer>{/* Footer */}</footer>
</body>
</html>
);
}
Dynamic routes use square brackets for parameters:
// app/blog/[slug]/page.tsx
interface PageProps {
params: { slug: string };
}
export default function BlogPost({ params }: PageProps) {
return <article>Post: {params.slug}</article>;
}
Create a loading.tsx
file for automatic loading UI:
// app/blog/loading.tsx
export default function Loading() {
return <div>Loading...</div>;
}
Fetch data directly in server components:
async function getPosts() {
const res = await fetch('https://api.example.com/posts');
return res.json();
}
export default async function BlogPage() {
const posts = await getPosts();
return (
<div>
{posts.map(post => (
<article key={post.id}>{post.title}</article>
))}
</div>
);
}
The App Router represents a significant evolution in how we build React applications. By embracing server components and streaming, we can create faster, more efficient web applications.
Happy coding!