Covers the App Router in Next.js 15 and 16.
Create and run
_10npx create-next-app@latest my-app_10npm run dev # localhost:3000_10npm run build # production build_10npm start # serve the build
Special files
| File | Purpose |
|---|---|
page.tsx | The route's UI |
layout.tsx | Shared shell, keeps state |
loading.tsx | Suspense fallback |
error.tsx | Error boundary (client) |
not-found.tsx | 404 for the segment |
route.ts | API handler |
Routes
_10app/page.tsx /_10app/blog/page.tsx /blog_10app/blog/[slug]/page.tsx /blog/hello_10app/docs/[...all]/page.tsx /docs/a/b_10app/(shop)/cart/page.tsx /cart
Dynamic params
_10type Props = { params: Promise<{ slug: string }> };_10_10export default async function Post({ params }: Props) {_10 const { slug } = await params;_10 return <h1>{slug}</h1>;_10}_10_10export async function generateStaticParams() {_10 return [{ slug: 'hello' }];_10}
Server and client
_10// Server component by default: can be async,_10// can read the database, ships no JS._10export default async function Page() {_10 const posts = await db.post.findMany();_10 return <List posts={posts} />;_10}_10_10'use client'; // top of a file that needs_10 // state, effects or events
Data and caching
_10await fetch(url, { cache: 'force-cache' });_10await fetch(url, { next: { revalidate: 3600 } });_10export const revalidate = 3600; // whole route_10_10revalidatePath('/blog'); // after a write_10revalidateTag('posts');
Server actions
_10async function create(formData: FormData) {_10 'use server';_10 await db.post.create({_10 data: { title: String(formData.get('title')) },_10 });_10 revalidatePath('/blog');_10}_10_10<form action={create}>...</form>
Route handlers
_10// app/api/items/route.ts_10export async function GET(req: Request) {_10 return Response.json({ items: [] });_10}_10export async function POST(req: Request) {_10 const body = await req.json();_10 return Response.json(body, { status: 201 });_10}
Metadata
_10export const metadata: Metadata = {_10 title: 'Blog',_10 description: 'Latest posts',_10};_10_10export async function generateMetadata({ params }) {_10 const { slug } = await params;_10 return { title: slug };_10}