DM
Technical reference

Next.js Cheatsheet

The React framework for production

Getting Started

Create App

npx create-next-app@latest my-app
cd my-app
npm run dev

File-Based Routing

Any `page.tsx` inside `app/` becomes a route.

app/page.tsx        -> /
app/about/page.tsx  -> /about

Routing (App Router)

Dynamic Route

// app/[topic]/page.tsx
export default function Page({ params }: { params: { topic: string } }) {
  return <h1>{params.topic}</h1>;
}

Nested Layout

// app/dashboard/layout.tsx
export default function Layout({ children }: { children: React.ReactNode }) {
  return <section>{children}</section>;
}

Loading & Error States

Special files that automatically wrap the route segment.

app/dashboard/loading.tsx
app/dashboard/error.tsx

Data Fetching

Server Component Fetch

Fetching directly in a Server Component runs on the server, no client JS needed.

export default async function Page() {
  const res = await fetch("https://api.example.com/data");
  const data = await res.json();
  return <div>{data.title}</div>;
}

Caching a Request

Revalidate cached data every 60 seconds (ISR).

fetch(url, { next: { revalidate: 60 } });

Opt Out of Caching

fetch(url, { cache: "no-store" });

API Routes

Route Handler (GET)

// app/api/hello/route.ts
export async function GET() {
  return Response.json({ message: "Hello" });
}

Route Handler (POST)

export async function POST(request: Request) {
  const body = await request.json();
  return Response.json({ received: body });
}

Client vs Server Components

Client Component

Add "use client" at the top when you need state, effects, or browser APIs.

"use client";

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Navigation

Link Component

import Link from "next/link";

<Link href="/about">About</Link>

Programmatic Navigation

"use client";
import { useRouter } from "next/navigation";

const router = useRouter();
router.push("/dashboard");

Metadata & Config

Static Metadata

export const metadata = {
  title: "My App",
  description: "An example Next.js app",
};

Environment Variables

Prefix with NEXT_PUBLIC_ to expose a variable to the browser.

// .env.local
NEXT_PUBLIC_API_URL=https://api.example.com