# Code Reference — Next.js

_14 pages_

---
# Next.js (/docs/nextjs)



# Next.js [#nextjs]

App Router, RSC, deployment.

Browse the sidebar for every cheat sheet in this section.

## Sections [#sections]

*All notes are listed in the sidebar.*


---

# App Router (/docs/nextjs/app-router)



# App Router [#app-router]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

The App Router uses the `app/` directory for routes, layouts, loading UI, and nested segments. Folders define URL segments; special files define UI and behavior.

## 🔧 Core concepts [#-core-concepts]

| File            | Role                                                     |
| --------------- | -------------------------------------------------------- |
| `page.tsx`      | UI for a route (required for that URL)                   |
| `layout.tsx`    | Shared UI wrapping children; persists across navigations |
| `loading.tsx`   | Instant loading UI (Suspense boundary)                   |
| `error.tsx`     | Error boundary for the segment                           |
| `not-found.tsx` | 404 UI                                                   |
| `route.ts`      | Route Handler (API endpoint)                             |
| `template.tsx`  | Like layout but remounts on navigation                   |
| `default.tsx`   | Fallback for parallel routes                             |

| Convention    | Meaning                      |
| ------------- | ---------------------------- |
| `[id]`        | Dynamic segment              |
| `[...slug]`   | Catch-all                    |
| `[[...slug]]` | Optional catch-all           |
| `(group)`     | Route group — no URL segment |
| `@slot`       | Parallel route slot          |

## 💡 Examples [#-examples]

**Nested layout:**

```
app/
  layout.tsx
  page.tsx          → /
  blog/
    layout.tsx
    page.tsx        → /blog
    [slug]/
      page.tsx      → /blog/:slug
```

**Dynamic page:**

```tsx
// app/blog/[slug]/page.tsx
export default async function Post({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  return <h1>{slug}</h1>;
}
```

**Route group (no URL impact):**

```
app/(marketing)/about/page.tsx  → /about
app/(shop)/cart/page.tsx        → /cart
```

## ⚠️ Pitfalls [#️-pitfalls]

* `layout.tsx` does not remount on soft navigation — don't put one-shot client state there expecting reset.
* `params` and `searchParams` are async in recent Next.js — await them.
* A folder without `page.tsx` is not a reachable route by itself.

## 🔗 Related [#-related]

* [pages\_router.md](/docs/nextjs/pages-router)
* [server\_components.md](/docs/nextjs/server-components)
* [route\_handlers.md](/docs/nextjs/route-handlers)
* [link\_navigation.md](/docs/nextjs/link-navigation)
* [getting\_started.md](/docs/nextjs/getting-started)


---

# Caching (/docs/nextjs/caching)



# Caching [#caching]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

App Router caching spans the Request Memoization, Data Cache, Full Route Cache, and Router Cache. Defaults favor static where possible; opt into dynamic when data must be fresh.

## 🔧 Core concepts [#-core-concepts]

| Cache               | What it stores                                |
| ------------------- | --------------------------------------------- |
| Request Memoization | Dedupes identical `fetch` in one render pass  |
| Data Cache          | Persistent server fetch cache across requests |
| Full Route Cache    | Pre-rendered HTML/RSC payload at build        |
| Router Cache        | Client-side cache of visited segments         |

| Control                                       | Effect                               |
| --------------------------------------------- | ------------------------------------ |
| `fetch(url, \{ cache: 'no-store' \})`         | Skip Data Cache                      |
| `fetch(url, \{ next: \{ revalidate: N \} \})` | ISR-style revalidate every N seconds |
| `revalidatePath` / `revalidateTag`            | On-demand invalidation               |
| `export const dynamic = 'force-dynamic'`      | Always dynamic route                 |
| `export const revalidate = 60`                | Segment revalidate window            |

## 💡 Examples [#-examples]

**Time-based revalidation:**

```ts
const res = await fetch("https://api.example.com/items", {
  next: { revalidate: 3600, tags: ["items"] },
});
```

**On-demand revalidate (Server Action / Route Handler):**

```ts
import { revalidateTag } from "next/cache";

export async function refreshItems() {
  revalidateTag("items");
}
```

**Force dynamic:**

```ts
export const dynamic = "force-dynamic";
```

## ⚠️ Pitfalls [#️-pitfalls]

* Stale UI after mutations usually means missing `revalidatePath`/`revalidateTag`.
* Caching behavior differs between local `next dev` and production builds.
* Mixing `no-store` fetches inside otherwise static layouts can turn the whole route dynamic.

## 🔗 Related [#-related]

* [server\_components.md](/docs/nextjs/server-components)
* [route\_handlers.md](/docs/nextjs/route-handlers)
* [deployment.md](/docs/nextjs/deployment)
* [app\_router.md](/docs/nextjs/app-router)


---

# Deployment (/docs/nextjs/deployment)



# Deployment [#deployment]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Deploy Next.js with a Node server (`next start`), a Platform-as-a-Service (Vercel, etc.), or a static export when the app has no server-only features.

## 🔧 Core concepts [#-core-concepts]

| Mode          | Command / config            | Fits                     |
| ------------- | --------------------------- | ------------------------ |
| Node server   | `next build` → `next start` | SSR, Route Handlers, ISR |
| Vercel        | Git integration             | Full Next.js feature set |
| Docker        | Multi-stage Node image      | Self-hosted              |
| Static export | `output: 'export'`          | Fully static sites only  |

| Checklist               | Why                            |
| ----------------------- | ------------------------------ |
| Set production env vars | Secrets and `NEXT_PUBLIC_*`    |
| `NODE_ENV=production`   | Optimizations                  |
| Health endpoint         | Orchestrators / load balancers |
| Match Node version      | Avoid native module mismatches |

## 💡 Examples [#-examples]

**Build & start:**

```shellscript
npm run build
npm run start
```

**Static export (`next.config.ts`):**

```ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "export",
};
export default nextConfig;
```

**Docker (sketch):**

```dockerfile
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
EXPOSE 3000
CMD ["npm", "start"]
```

## ⚠️ Pitfalls [#️-pitfalls]

* Static export cannot use server features (SSR cookies, many Route Handlers, ISR the same way).
* Forgetting to set env vars on the host causes runtime crashes that never appeared locally.
* Binding only to `localhost` inside containers breaks external access — listen on `0.0.0.0` when required by the host.

## 🔗 Related [#-related]

* [env.md](/docs/nextjs/env)
* [caching.md](/docs/nextjs/caching)
* [middleware.md](/docs/nextjs/middleware)
* [getting\_started.md](/docs/nextjs/getting-started)
* [Docker/getting\_started.md](/docs/nextjs/../docker/getting-started)


---

# Environment Variables (/docs/nextjs/env)



# Environment Variables [#environment-variables]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Next.js loads `.env*` files and exposes variables to Node (server) and, with a prefix, to the browser bundle. Never ship secrets with the public prefix.

## 🔧 Core concepts [#-core-concepts]

| File                                   | Typical use                         |
| -------------------------------------- | ----------------------------------- |
| `.env`                                 | Default for all environments        |
| `.env.local`                           | Local secrets (gitignored)          |
| `.env.development` / `.env.production` | Env-specific defaults               |
| `.env*.local`                          | Overrides; highest priority locally |

| Access                             | Visibility                                 |
| ---------------------------------- | ------------------------------------------ |
| `process.env.MY_SECRET`            | Server only                                |
| `process.env.NEXT_PUBLIC_*`        | Inlined into client JS                     |
| `NEXT_PUBLIC_*` in Edge/Middleware | Available if set at build/runtime per host |

## 💡 Examples [#-examples]

**`.env.local`:**

```shellscript
DATABASE_URL=postgres://...
NEXT_PUBLIC_APP_URL=http://localhost:3000
```

**Server usage:**

```ts
const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is required");
```

**Client usage:**

```tsx
"use client";
export function Banner() {
  return <p>{process.env.NEXT_PUBLIC_APP_URL}</p>;
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Changing env vars often requires restarting `next dev` / rebuilding.
* `NEXT_PUBLIC_` values are baked in at build time for many hosts — treat them as public.
* Don't put API keys in `NEXT_PUBLIC_*` even "temporarily".

## 🔗 Related [#-related]

* [server\_components.md](/docs/nextjs/server-components)
* [deployment.md](/docs/nextjs/deployment)
* [middleware.md](/docs/nextjs/middleware)
* [caching.md](/docs/nextjs/caching)


---

# Getting Started with Next.js (/docs/nextjs/getting-started)



# Getting Started with Next.js [#getting-started-with-nextjs]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Next.js is a React framework for full-stack web apps. It adds routing, rendering modes, image optimization, and deployment conventions on top of React.

## 🔧 Core concepts [#-core-concepts]

| Idea         | Meaning                                               |
| ------------ | ----------------------------------------------------- |
| App Router   | File-based routing under `app/` (default in new apps) |
| Pages Router | Legacy file-based routing under `pages/`              |
| RSC          | React Server Components — default in App Router       |
| SSR / SSG    | Server-render on request vs pre-render at build       |
| Turbopack    | Fast bundler used by `next dev` (newer versions)      |

**Create a project:**

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

| Script       | Purpose                  |
| ------------ | ------------------------ |
| `next dev`   | Local development server |
| `next build` | Production build         |
| `next start` | Serve production build   |
| `next lint`  | Run ESLint               |

## 💡 Examples [#-examples]

**Minimal `app/page.tsx`:**

```tsx
export default function Home() {
  return <h1>Hello Next.js</h1>;
}
```

**`package.json` scripts:**

```json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}
```

**Check version:**

```shellscript
npx next --version
```

## ⚠️ Pitfalls [#️-pitfalls]

* Mixing App Router (`app/`) and Pages Router (`pages/`) without a clear plan causes confusion.
* Client hooks (`useState`, `useEffect`) need `'use client'` in App Router.
* Forgetting `next build` before `next start` serves a stale or missing build.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [pages\_router.md](/docs/nextjs/pages-router)
* [server\_components.md](/docs/nextjs/server-components)
* [deployment.md](/docs/nextjs/deployment)
* [glossary.md](/docs/nextjs/glossary)


---

# Glossary (/docs/nextjs/glossary)



# Glossary [#glossary]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Alphabetical glossary of Next.js terms spanning App Router, rendering, caching, and deployment.

## 🔧 Core concepts [#-core-concepts]

| Term                 | Definition                                                          |
| -------------------- | ------------------------------------------------------------------- |
| App Router           | Routing system based on the `app/` directory and special files.     |
| CSR                  | Client-side rendering in the browser after JS loads.                |
| Dynamic segment      | Folder like `[id]` that captures a URL parameter.                   |
| Edge runtime         | Lightweight runtime for Middleware and some Route Handlers.         |
| Hydration            | Attaching client React to server-rendered HTML.                     |
| ISR                  | Incremental Static Regeneration — update static pages after deploy. |
| Layout               | Persistent UI wrapper (`layout.tsx`) shared by child routes.        |
| Middleware           | Edge code that runs before a request is completed.                  |
| Partial Prerendering | Hybrid static shell + dynamic holes (version-dependent).            |
| Prefetch             | Loading a route in the background via `Link`.                       |
| Route Handler        | `route.ts` exporting HTTP methods as an API endpoint.               |
| Route group          | `(name)` folder that organizes routes without affecting the URL.    |
| RSC                  | React Server Component rendered on the server by default.           |
| Soft navigation      | Client transition without full document reload.                     |
| SSG                  | Static Site Generation at build time.                               |
| SSR                  | Server-Side Rendering on each request.                              |
| Streaming            | Sending UI in chunks via Suspense / `loading.tsx`.                  |
| Turbopack            | Rust-based bundler used in modern `next dev`.                       |

## 💡 Examples [#-examples]

**Dynamic segment mental model:**

```
app/shop/[slug]/page.tsx  →  /shop/shoes
```

**RSC vs client:**

```tsx
// Server (default)
export default async function Page() { /* fetch, await */ }

// Client
"use client";
export function Widget() { /* useState, onClick */ }
```

## ⚠️ Pitfalls [#️-pitfalls]

* Glossaries drift — verify behavior against your installed Next.js major version.
* “Static” vs “dynamic” depends on APIs used (`cookies`, `headers`, `no-store`), not folder names alone.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/nextjs/getting-started)
* [app\_router.md](/docs/nextjs/app-router)
* [caching.md](/docs/nextjs/caching)
* [server\_components.md](/docs/nextjs/server-components)
* [README.md](/docs/nextjs)


---

# next/image (/docs/nextjs/image)



# next/image [#nextimage]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

`next/image` optimizes images: resizing, modern formats, lazy loading, and layout shift prevention via required dimensions or `fill`.

## 🔧 Core concepts [#-core-concepts]

| Prop               | Purpose                                         |
| ------------------ | ----------------------------------------------- |
| `src`              | Path or remote URL                              |
| `alt`              | Required accessibility text                     |
| `width` / `height` | Intrinsic size (static imports can infer)       |
| `fill`             | Fill parent (parent needs `position: relative`) |
| `sizes`            | Hint for responsive `srcset`                    |
| `priority`         | Preload above-the-fold images                   |
| `placeholder`      | `"blur"` or `"empty"`                           |

| Config (`next.config`)              | Purpose               |
| ----------------------------------- | --------------------- |
| `images.remotePatterns`             | Allow remote hosts    |
| `images.formats`                    | AVIF/WebP preferences |
| `images.deviceSizes` / `imageSizes` | Generated widths      |

## 💡 Examples [#-examples]

**Local image:**

```tsx
import Image from "next/image";
import hero from "@/public/hero.jpg";

export function Hero() {
  return <Image src={hero} alt="Product hero" priority />;
}
```

**Remote with sizes:**

```tsx
<Image
  src="https://cdn.example.com/photo.jpg"
  alt="Photo"
  width={800}
  height={600}
  sizes="(max-width: 768px) 100vw, 800px"
/>
```

**Fill layout:**

```tsx
<div style={{ position: "relative", width: "100%", height: 320 }}>
  <Image src="/banner.jpg" alt="Banner" fill style={{ objectFit: "cover" }} />
</div>
```

## ⚠️ Pitfalls [#️-pitfalls]

* Remote images fail without `remotePatterns` (or legacy `domains`).
* Missing `sizes` with `fill` can download oversized images on mobile.
* Overusing `priority` defeats lazy loading and hurts LCP for other assets.

## 🔗 Related [#-related]

* [link\_navigation.md](/docs/nextjs/link-navigation)
* [metadata.md](/docs/nextjs/metadata)
* [caching.md](/docs/nextjs/caching)
* [deployment.md](/docs/nextjs/deployment)


---

# Link & Navigation (/docs/nextjs/link-navigation)



# Link & Navigation [#link--navigation]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Use `next/link` for client-side soft navigation and `next/navigation` hooks for programmatic routing in the App Router. Prefer Link over raw `<a>` for internal routes.

## 🔧 Core concepts [#-core-concepts]

| API                               | Router       | Purpose                              |
| --------------------------------- | ------------ | ------------------------------------ |
| `Link`                            | Both         | Prefetch + soft navigate             |
| `useRouter` (`next/navigation`)   | App          | `push`, `replace`, `refresh`, `back` |
| `usePathname` / `useSearchParams` | App          | Read location                        |
| `useRouter` (`next/router`)       | Pages        | Legacy router                        |
| `redirect` / `notFound`           | App (Server) | Server-side navigation / 404         |

| `Link` prop | Notes                                               |
| ----------- | --------------------------------------------------- |
| `href`      | String or URL object                                |
| `prefetch`  | Default true in many cases; disable for rare routes |
| `replace`   | Replace history entry                               |
| `scroll`    | Scroll to top (default true)                        |

## 💡 Examples [#-examples]

**Basic Link:**

```tsx
import Link from "next/link";

export function Nav() {
  return <Link href="/docs">Docs</Link>;
}
```

**Programmatic navigation (Client):**

```tsx
"use client";
import { useRouter } from "next/navigation";

export function Go() {
  const router = useRouter();
  return <button onClick={() => router.push("/dashboard")}>Open</button>;
}
```

**Server redirect:**

```tsx
import { redirect } from "next/navigation";

export default function Page() {
  redirect("/login");
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* `useRouter` from `next/router` vs `next/navigation` — wrong import breaks App Router pages.
* `useSearchParams()` can force a client Suspense boundary — wrap accordingly.
* External URLs should use `<a>` (or `Link` with absolute URL); don't treat them like soft navigations for SEO-critical exit links without care.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [pages\_router.md](/docs/nextjs/pages-router)
* [middleware.md](/docs/nextjs/middleware)
* [server\_components.md](/docs/nextjs/server-components)


---

# Metadata (/docs/nextjs/metadata)



# Metadata [#metadata]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

App Router metadata APIs set `<title>`, `<meta>`, Open Graph, icons, and more — statically via `metadata` export or dynamically via `generateMetadata`.

## 🔧 Core concepts [#-core-concepts]

| API                     | When                                             |
| ----------------------- | ------------------------------------------------ |
| `export const metadata` | Static, known at build                           |
| `generateMetadata`      | Dynamic per request/params                       |
| `generateViewport`      | Viewport / theme-color                           |
| File conventions        | `favicon.ico`, `opengraph-image.tsx`, `icon.tsx` |

| Field                   | Purpose                              |
| ----------------------- | ------------------------------------ |
| `title`                 | Document title (supports `template`) |
| `description`           | Meta description                     |
| `openGraph` / `twitter` | Social cards                         |
| `robots`                | Indexing directives                  |
| `alternates.canonical`  | Canonical URL                        |

## 💡 Examples [#-examples]

**Static metadata:**

```tsx
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: { default: "My App", template: "%s · My App" },
  description: "Product docs and dashboard",
};
```

**Dynamic metadata:**

```tsx
export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  return { title: slug };
}
```

**Root layout title template:**

```tsx
// app/layout.tsx
export const metadata = {
  title: { default: "Home", template: "%s | Acme" },
};
```

## ⚠️ Pitfalls [#️-pitfalls]

* Metadata in Client Components is ignored — keep it in Server layouts/pages.
* Duplicate titles across nested layouts can fight; use `template` deliberately.
* Social crawlers need absolute OG image URLs in production.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [server\_components.md](/docs/nextjs/server-components)
* [image.md](/docs/nextjs/image)
* [getting\_started.md](/docs/nextjs/getting-started)


---

# Middleware (/docs/nextjs/middleware)



# Middleware [#middleware]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Middleware runs on the Edge before a request is completed. Use it for redirects, rewrites, auth gates, A/B headers, and geo-based routing — not heavy business logic.

## 🔧 Core concepts [#-core-concepts]

| API                       | Role                             |
| ------------------------- | -------------------------------- |
| `middleware.ts`           | File at project root or `src/`   |
| `NextRequest`             | Incoming request                 |
| `NextResponse.next()`     | Continue                         |
| `NextResponse.redirect()` | Redirect                         |
| `NextResponse.rewrite()`  | Internal rewrite                 |
| `matcher`                 | Limit which paths run middleware |

| Runtime                     | Notes                                  |
| --------------------------- | -------------------------------------- |
| Edge                        | Default; limited Node APIs             |
| Node (experimental options) | Check current Next.js docs for support |

## 💡 Examples [#-examples]

**Redirect unauthenticated users:**

```ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const token = req.cookies.get("session")?.value;
  if (!token && req.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*"],
};
```

**Rewrite:**

```ts
export function middleware(req: NextRequest) {
  if (req.nextUrl.pathname === "/old") {
    return NextResponse.rewrite(new URL("/new", req.url));
  }
  return NextResponse.next();
}
```

**Set a header:**

```ts
export function middleware(req: NextRequest) {
  const res = NextResponse.next();
  res.headers.set("x-pathname", req.nextUrl.pathname);
  return res;
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Middleware runs on many requests — keep it fast and matcher-scoped.
* Avoid DB calls and large dependency graphs in Edge middleware.
* Infinite redirect loops are easy if login ↔ protected matchers overlap badly.

## 🔗 Related [#-related]

* [route\_handlers.md](/docs/nextjs/route-handlers)
* [env.md](/docs/nextjs/env)
* [app\_router.md](/docs/nextjs/app-router)
* [deployment.md](/docs/nextjs/deployment)


---

# Pages Router (/docs/nextjs/pages-router)



# Pages Router [#pages-router]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

The Pages Router is the original Next.js routing model: each file under `pages/` maps to a URL. Still supported and common in older codebases.

## 🔧 Core concepts [#-core-concepts]

| File / pattern        | URL                  |
| --------------------- | -------------------- |
| `pages/index.tsx`     | `/`                  |
| `pages/about.tsx`     | `/about`             |
| `pages/blog/[id].tsx` | `/blog/:id`          |
| `pages/api/hello.ts`  | `/api/hello`         |
| `pages/_app.tsx`      | App wrapper          |
| `pages/_document.tsx` | Custom HTML document |
| `pages/404.tsx`       | Custom 404           |

| Data API             | When it runs                     |
| -------------------- | -------------------------------- |
| `getStaticProps`     | Build time (SSG)                 |
| `getStaticPaths`     | Build time paths for dynamic SSG |
| `getServerSideProps` | Every request (SSR)              |

## 💡 Examples [#-examples]

**Static page with props:**

```tsx
export async function getStaticProps() {
  return { props: { title: "Home" } };
}

export default function Home({ title }: { title: string }) {
  return <h1>{title}</h1>;
}
```

**Dynamic SSR:**

```tsx
export async function getServerSideProps(ctx: { params: { id: string } }) {
  return { props: { id: ctx.params.id } };
}
```

**API route:**

```ts
// pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ ok: true });
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Don't put secrets in `getStaticProps` props — they ship to the client HTML.
* `_document.tsx` only runs on the server; no React context/hooks from `_app` there.
* Prefer App Router for new projects unless you have a Pages-only constraint.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [route\_handlers.md](/docs/nextjs/route-handlers)
* [link\_navigation.md](/docs/nextjs/link-navigation)
* [Comparisons/pages\_vs\_app\_router.md](/docs/nextjs/../comparisons/pages-vs-app-router)


---

# Route Handlers (/docs/nextjs/route-handlers)



# Route Handlers [#route-handlers]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Route Handlers live in `app/**/route.ts` (or `.js`) and export HTTP method functions. They replace many `pages/api` use cases in the App Router.

## 🔧 Core concepts [#-core-concepts]

| Export             | HTTP method     |
| ------------------ | --------------- |
| `GET`              | Read            |
| `POST`             | Create / submit |
| `PUT` / `PATCH`    | Update          |
| `DELETE`           | Delete          |
| `HEAD` / `OPTIONS` | Meta / CORS     |

| Helper         | Use                                   |
| -------------- | ------------------------------------- |
| `NextRequest`  | Extended Request (cookies, `nextUrl`) |
| `NextResponse` | JSON, redirects, cookies              |
| `params`       | Dynamic segment values                |

## 💡 Examples [#-examples]

**JSON GET:**

```ts
// app/api/hello/route.ts
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({ message: "hi" });
}
```

**POST with body:**

```ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const body = await req.json();
  return NextResponse.json({ received: body }, { status: 201 });
}
```

**Dynamic segment:**

```ts
// app/api/users/[id]/route.ts
export async function GET(
  _req: Request,
  ctx: { params: Promise<{ id: string }> },
) {
  const { id } = await ctx.params;
  return Response.json({ id });
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Don't export a `page.tsx` and `route.ts` for the same path segment.
* Default caching of `GET` can surprise you — set `export const dynamic = 'force-dynamic'` when needed.
* Large file uploads need streaming/`FormData` care; don't assume unlimited body size.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [middleware.md](/docs/nextjs/middleware)
* [caching.md](/docs/nextjs/caching)
* [pages\_router.md](/docs/nextjs/pages-router)


---

# Server Components (/docs/nextjs/server-components)



# Server Components [#server-components]

*Next.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

In the App Router, components are Server Components by default. They render on the server, can access backend resources directly, and send a compact RSC payload to the client.

## 🔧 Core concepts [#-core-concepts]

| Kind             | Directive      | Can use                                  |
| ---------------- | -------------- | ---------------------------------------- |
| Server Component | (default)      | `async`, DB, secrets, `fetch` with cache |
| Client Component | `'use client'` | hooks, events, browser APIs              |

| Rule              | Detail                                           |
| ----------------- | ------------------------------------------------ |
| Pass data down    | Server → Client via serializable props           |
| Import direction  | Client can import Client; Server can import both |
| No server secrets | Never pass secrets as Client props               |

**Server-only APIs:** `fs`, DB clients, private env vars, `cookies()`, `headers()`.

## 💡 Examples [#-examples]

**Async Server Component:**

```tsx
async function Users() {
  const res = await fetch("https://api.example.com/users", {
    next: { revalidate: 60 },
  });
  const users = await res.json();
  return <ul>{users.map((u: { id: string; name: string }) => (
    <li key={u.id}>{u.name}</li>
  ))}</ul>;
}
```

**Client boundary:**

```tsx
"use client";

import { useState } from "react";

export function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>{n}</button>;
}
```

**Compose both:**

```tsx
// app/page.tsx (Server)
import { Counter } from "./Counter";

export default function Page() {
  return (
    <main>
      <h1>Dashboard</h1>
      <Counter />
    </main>
  );
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Putting `'use client'` at the top of a large tree ships more JS than needed — push the boundary down.
* Non-serializable props (functions, class instances) cannot cross the server→client boundary.
* `useEffect` / `onClick` in a Server Component is a build error.

## 🔗 Related [#-related]

* [app\_router.md](/docs/nextjs/app-router)
* [caching.md](/docs/nextjs/caching)
* [env.md](/docs/nextjs/env)
* [route\_handlers.md](/docs/nextjs/route-handlers)

