Next.js App Router Cheat Sheet

Quick reference guide for Next.js App Router: Routing, Server Components, Server Actions, Caching, and Metadata API.

Modern Frontend
nextjs
react
app-router

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.

Table
FilenamePurposeExecution Context
page.tsxUnique UI route path entry pointServer Component (default)
layout.tsxShared wrapper UI for route subtreesServer Component
loading.tsxSuspense boundary UI during page fetchServer Component (default)
error.tsxError boundary UI catch blockClient Component ("use client")
not-found.tsx404 Not Found UI for route segmentServer / Client
route.tsCustom HTTP REST/API EndpointServer (Node.js/Edge)

Route Parameters & Data Fetching

tsx
// 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.

tsx
// 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.

tsx
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 with fetch(url, { next: { tags: ['tag-name'] } }) for targeted data cache invalidation across routes.