Quick Reference Next.js Cheatsheet
The App Router on one page — file conventions, links and dynamic routes, Server and Client
Components, fetching and cache, Server Actions, metadata, route handlers, images, environment
variables, and interview traps.
10 sections 9 tables 17 code snippets Create and run npx create-next-app@latest my-app
cd my-app
npm run dev
npm run build
npm run start
npm run lint Smallest page export default function HomePage() {
return (
<main>
<h1>LearnCodeGuru</h1>
</main>
);
} Examples on this page use the App Router and Next.js 15 or newer. params and searchParams are Promises, and fetch is not cached unless you opt in. 📁 App Router File Conventions Root layout export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
} Only the root layout renders <html> and <body>. Nested layouts render a fragment or a wrapper element. Dynamic segment type Props = {
params: Promise<{ slug: string }>;
};
export default async function PostPage({ params }: Props) {
const { slug } = await params;
return <article>{slug}</article>;
} Link and redirect import Link from "next/link";
import { notFound, redirect } from "next/navigation";
export function Nav() {
return <Link href="/blog">Blog</Link>;
}
export async function loadPost(slug: string) {
const post = await findPost(slug);
if (!post) notFound();
if (post.movedTo) redirect(post.movedTo);
return post;
} 🧩 Server & Client Components Client component "use client";
import { useState } from "react";
export default function Counter() {
const [n, setN] = useState(0);
return (
<button onClick={() => setN(n + 1)}>{n}</button>
);
} Pass a server tree through
"use client";
export function ClientShell({ children }: { children: React.ReactNode }) {
return <section className="card">{children}</section>;
}
export default function Page() {
return (
<ClientShell>
<PostList />
</ClientShell>
);
} "use client" marks a boundary. Imports from that file also run on the client. Do not import server-only modules there. Fetch in a Server Component export default async function Page() {
const res = await fetch("https://api.example.com/posts", {
next: { revalidate: 60 },
});
if (!res.ok) throw new Error("posts failed");
const posts: { id: string; title: string }[] = await res.json();
return <p>{posts.length} posts</p>;
} Always fresh const res = await fetch(url, { cache: "no-store" });
export const dynamic = "force-dynamic"; Form posts to the server import { revalidatePath } from "next/cache";
async function save(formData: FormData) {
"use server";
const title = String(formData.get("title") ?? "");
await db.post.create({ title });
revalidatePath("/blog");
}
export default function NewPost() {
return (
<form action={save}>
<input name="title" required />
<button type="submit">Save</button>
</form>
);
} Static metadata import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Blog",
description: "Posts from LearnCodeGuru",
}; Per-request metadata import type { Metadata } from "next";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
return { title: slug };
} Do not export both metadata and generateMetadata from the same file. The title template belongs on the root layout: title: { default: "LearnCodeGuru", template: "%s | LearnCodeGuru" }. app/api/posts/route.ts import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ ok: true });
}
export async function POST(request: Request) {
const body = await request.json();
return NextResponse.json(body, { status: 201 });
} A segment has either page.tsx or route.ts, not both. GET handlers are uncached in Next.js 15 unless you opt in. next/image and next/font import Image from "next/image";
import { Inter } from "next/font/google";
const inter = Inter({ subsets: ["latin"] });
export default function Cover() {
return (
<Image
className={inter.className}
src="/cover.jpg"
alt="Course cover"
width={1200}
height={630}
priority
/>
);
} Environment variables const dbUrl = process.env.DATABASE_URL;
const site = process.env.NEXT_PUBLIC_SITE_URL; Remote images need images.remotePatterns in next.config.ts. priority is for the one image above the fold, not every image. Await the params export default async function Page({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
return <h1>{slug}</h1>;
} Client hook import "use client";
import { useRouter } from "next/navigation";
export function BackButton() {
const router = useRouter();
return <button onClick={() => router.back()}>Back</button>;
} How to use this page: skim the jump chips, then type a route in app/. Confirm a Server Component can render data with no useEffect, and that a button with state lives in a file that starts with "use client". |