Next.js App Router Cheat Sheet
Quick reference guide for Next.js App Router: Routing, Server Components, Server Actions, Caching, and Metadata API.
Next.js is a React framework for building full-stack web applications. The App Router introduces React Server Components, file-system routing conventions, Server Actions, and granular caching mechanisms.
Special File Conventions
The App Router uses folder hierarchy and specific filenames to define UI routes and layouts.
| Filename | Purpose | Execution Context |
|---|---|---|
page.tsx | Unique UI route path entry point | Server Component (default) |
layout.tsx | Shared wrapper UI for route subtrees | Server Component |
loading.tsx | Suspense boundary UI during page fetch | Server Component (default) |
error.tsx | Error boundary UI catch block | Client Component ("use client") |
not-found.tsx | 404 Not Found UI for route segment | Server / Client |
route.ts | Custom HTTP REST/API Endpoint | Server (Node.js/Edge) |
Route Parameters & Data Fetching
// app/blog/[slug]/page.tsx
interface Props {
params: Promise<{ slug: string }>;
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}
export default async function BlogPost({ params, searchParams }: Props) {
const { slug } = await params;
const { ref } = await searchParams;
// Server-side data fetching directly in component
const post = await fetch(`https://api.example.com/posts/${slug}`, {
next: { revalidate: 3600 } // Revalidate every hour
}).then((res) => res.json());
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
);
}
Server Actions & Revalidation
Server Actions enable async server functions to be triggered directly from client forms or event handlers.
// app/actions.ts
"use server";
import { revalidatePath } from "next/cache";
export async function createPost(formData: FormData) {
const title = formData.get("title") as string;
// Database save mutation
await db.post.create({ data: { title } });
// Invalidate cached page path
revalidatePath("/posts");
}
Metadata & SEO Configuration
Dynamic metadata helps search engines index pages accurately.
import type { Metadata } from "next";
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
const { id } = await params;
const item = await getItem(id);
return {
title: item.title,
description: item.summary,
openGraph: {
title: item.title,
images: [item.imageUrl],
},
};
}
Common Pitfalls & Tips
[!IMPORTANT] Files in the App Router are Server Components by default. Add
"use client"at the top of the file only when using React Hooks (useState,useEffect) or browser DOM event listeners.
[!TIP] Use
revalidateTag('tag-name')along withfetch(url, { next: { tags: ['tag-name'] } })for targeted data cache invalidation across routes.