Master Next.js 14 App Router with server components, layouts, and streaming
# Next.js 14 App Router Complete Guide
Master Next.js 14 App Router with Google Antigravity IDE. This comprehensive guide covers server components, routing patterns, data fetching, and performance optimization for modern React applications.
## Why App Router?
Next.js 14 App Router represents a paradigm shift with React Server Components, streaming, and improved data fetching. Google Antigravity IDE's Gemini 3 engine provides intelligent patterns for optimal App Router usage.
## Project Structure
```
app/
├── layout.tsx # Root layout
├── page.tsx # Home page
├── loading.tsx # Loading UI
├── error.tsx # Error boundary
├── not-found.tsx # 404 page
├── globals.css # Global styles
├── (marketing)/ # Route group
│ ├── layout.tsx
│ ├── about/page.tsx
│ └── contact/page.tsx
├── dashboard/ # Protected routes
│ ├── layout.tsx
│ ├── page.tsx
│ └── settings/
│ └── page.tsx
└── api/ # API routes
└── users/
└── route.ts
```
## Server Components
```typescript
// app/products/page.tsx
import { Suspense } from "react";
import { ProductList } from "@/components/ProductList";
import { ProductListSkeleton } from "@/components/skeletons";
// This is a Server Component by default
export default async function ProductsPage() {
return (
<div className="container mx-auto py-8">
<h1 className="text-3xl font-bold mb-6">Products</h1>
<Suspense fallback={<ProductListSkeleton />}>
<ProductList />
</Suspense>
</div>
);
}
// components/ProductList.tsx - Server Component
async function getProducts() {
const res = await fetch("https://api.example.com/products", {
next: { revalidate: 3600 }, // Cache for 1 hour
});
if (!res.ok) throw new Error("Failed to fetch products");
return res.json();
}
export async function ProductList() {
const products = await getProducts();
return (
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
```
## Client Components
```typescript
// components/AddToCartButton.tsx
"use client";
import { useState, useTransition } from "react";
import { addToCart } from "@/actions/cart";
interface AddToCartButtonProps {
productId: string;
}
export function AddToCartButton({ productId }: AddToCartButtonProps) {
const [isPending, startTransition] = useTransition();
const [added, setAdded] = useState(false);
const handleClick = () => {
startTransition(async () => {
await addToCart(productId);
setAdded(true);
setTimeout(() => setAdded(false), 2000);
});
};
return (
<button
onClick={handleClick}
disabled={isPending}
className="btn btn-primary"
>
{isPending ? "Adding..." : added ? "Added!" : "Add to Cart"}
</button>
);
}
```
## Server Actions
```typescript
// actions/cart.ts
"use server";
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";
export async function addToCart(productId: string) {
const cookieStore = cookies();
const cartId = cookieStore.get("cart_id")?.value;
await fetch(`https://api.example.com/cart/${cartId}/items`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ productId, quantity: 1 }),
});
revalidatePath("/cart");
}
export async function updateQuantity(itemId: string, quantity: number) {
// Update item quantity
revalidatePath("/cart");
}
```
## Dynamic Routes
```typescript
// app/blog/[slug]/page.tsx
import { Metadata } from "next";
import { notFound } from "next/navigation";
interface PageProps {
params: { slug: string };
}
export async function generateStaticParams() {
const posts = await fetch("https://api.example.com/posts").then((r) => r.json());
return posts.map((post: { slug: string }) => ({ slug: post.slug }));
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const post = await getPost(params.slug);
if (!post) return {};
return {
title: post.title,
description: post.excerpt,
openGraph: { images: [post.coverImage] },
};
}
export default async function BlogPostPage({ params }: PageProps) {
const post = await getPost(params.slug);
if (!post) notFound();
return <article>{/* Render post */}</article>;
}
```
## Parallel Routes
```typescript
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
analytics,
team,
}: {
children: React.ReactNode;
analytics: React.ReactNode;
team: React.ReactNode;
}) {
return (
<div className="grid grid-cols-12 gap-4">
<main className="col-span-8">{children}</main>
<aside className="col-span-4 space-y-4">
{analytics}
{team}
</aside>
</div>
);
}
```
## Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("auth_token")?.value;
if (request.nextUrl.pathname.startsWith("/dashboard")) {
if (!token) {
return NextResponse.redirect(new URL("/login", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};
```
## Best Practices
- Use Server Components by default
- Add "use client" only when needed
- Implement proper loading and error states
- Use generateStaticParams for static generation
- Apply route groups for organization
- Leverage parallel routes for complex layouts
Google Antigravity IDE provides intelligent App Router patterns and automatically suggests optimal component boundaries for your Next.js applications.This Next.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their next.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.