Skip to main content
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

Project & Scripts

Create and run

npx create-next-app@latest my-app
cd my-app
npm run dev          # http://localhost:3000
npm run build
npm run start        # serve the production build
npm run lint

Smallest page

export default function HomePage() {
  return (
    <main>
      <h1>LearnCodeGuru</h1>
    </main>
  );
}

Where code lives

FolderRole
app/App Router. Routes, layouts, and UI. Use this for new work
pages/Older Pages Router. Do not mix patterns in one route
public/Static files served from /. public/logo.png is /logo.png
next.config.tsRedirects, images, experimental flags

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>
  );
}

Special files

FileJob
page.tsxThe UI for that URL. Makes the route public
layout.tsxShared UI. Preserves state when you navigate inside it
loading.tsxSuspense fallback while the page waits
error.tsxError boundary. Must start with "use client"
not-found.tsxUI for notFound() and unknown URLs
route.tsHTTP handler instead of a page. No JSX
template.tsxLike a layout, but remounts on navigation

Only the root layout renders <html> and <body>. Nested layouts render a fragment or a wrapper element.

Routing & Link

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;
}

Folder to URL

FolderURL
app/page.tsx/
app/blog/page.tsx/blog
app/blog/[slug]/page.tsx/blog/hello
app/shop/[...slug]/page.tsx/shop/a/b catch-all
app/(marketing)/about/page.tsx/about. The (group) is not in the URL
app/blog/@modal/page.tsxParallel slot named modal

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

// ClientShell.tsx
"use client";

export function ClientShell({ children }: { children: React.ReactNode }) {
  return <section className="card">{children}</section>;
}

// page.tsx — server component passed as children
export default function Page() {
  return (
    <ClientShell>
      <PostList />
    </ClientShell>
  );
}

Which side

NeedUse
Read a database or secretServer Component (the default)
useState, useEffect, clicksClient Component. First line: "use client"
BothSmall client leaf. Keep data fetching on the server
A client parent around server UIPass the server UI as children

"use client" marks a boundary. Imports from that file also run on the client. Do not import server-only modules there.

Fetching & Caching

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";

Cache choices

OptionEffect
No option (Next.js 15+)fetch is uncached
cache: "force-cache"Reuse the response until you invalidate it
next: { revalidate: 60 }Refresh in the background after 60 seconds
cache: "no-store"Always hit the network
cookies() / headers()Opts the route into dynamic rendering

Forms & Server Actions

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>
  );
}

Rules

RuleWhy
"use server" on the function or the fileMarks a callable that runs only on the server
Validate formDataThe browser can send anything
revalidatePath / revalidateTagDrop stale cached pages after a write
redirect() after a mutationSend the user to the new page. Call it outside try/catch

Metadata

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" }.

Route Handlers

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 });
}

Status helpers

CallWhen
NextResponse.json(data)JSON with status 200
NextResponse.json(data, { status: 201 })Created
new Response(null, { status: 204 })No body
NextResponse.redirect(url)Redirect from a handler

A segment has either page.tsx or route.ts, not both. GET handlers are uncached in Next.js 15 unless you opt in.

Images, Fonts & Env

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;

What is public

NameVisible to
DATABASE_URLServer only. Safe for secrets
NEXT_PUBLIC_SITE_URLServer and browser. Never put a secret here
.env.localYour machine. Do not commit it

Remote images need images.remotePatterns in next.config.ts. priority is for the one image above the fold, not every image.

Interview Traps

Traps worth memorising

TrapWhat happensPrefer
useState in a Server ComponentBuild errorAdd "use client", or keep state in a child
useRouter from next/routerPages Router hook in the App RouterImport from next/navigation
Forgetting await paramsYou read a Promise, not the slugNext.js 15+: const { slug } = await params
"use client" on the root layoutThe whole tree becomes clientKeep the layout on the server
Importing a secret into a client fileThe value can ship to the browserRead secrets only in server code
NEXT_PUBLIC_ for an API keyAnyone can read the bundleServer-only env name
<img> for the heroNo size optimizationnext/image and priority
error.tsx without "use client"Invalid error boundaryClient directive on the first line
Expecting fetch to cacheNext.js 15 does not cache by defaultSet revalidate or force-cache
page.tsx and route.ts togetherConflicting segmentOne of them per folder
Client component marked asyncNot supportedFetch on the server, pass props down
redirect() inside try/catchThe redirect is swallowedCall redirect after the try

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".