[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ANR61GKRCYCMZYY3J4AD5Z":3,"skill-same:01M7ANR61GKRCYCMZYY3J4AD5Z":76},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":42,"commitSha":43,"skillDirectory":5,"forksCount":13,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":46,"install":47,"resources":59},"01M7ANR61GKRCYCMZYY3J4AD5Z","nextjs",null,"Use this skill for Next.js App Router patterns, Server Components, Server Actions, Cache Components, and framework-level optimizations. Covers Next.js 16 breaking changes including async params, proxy.ts migration, Cache Components with \"use cache\", and React 19.2 integration. For deploying to Cloudflare Workers, use the cloudflare-nextjs skill instead. This skill is deployment-agnostic and works with Vercel, AWS, self-hosted, or any platform.\n\nKeywords: Next.js 16, Next.js App Router, Next.js Pages Router, Server Components, React Server Components, Server Actions, Cache Components, use cache, Next.js 16 breaking changes, async params nextjs, proxy.ts migration, React 19.2, Next.js metadata, Next.js SEO, generateMetadata, static generation, dynamic rendering, streaming SSR, Suspense, parallel routes, intercepting routes, route groups, Next.js middleware, Next.js API routes, Route Handlers, revalidatePath, revalidateTag, next\u002Fnavigation, useSearchParams, turbopack, next.config","davidanthonyn\u002Fclaude-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ7JE1K98GRPH9Z57Z0R0W",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fnextjs\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: nextjs\ndescription: |\n  Use this skill for Next.js App Router patterns, Server Components, Server Actions, Cache Components, and framework-level optimizations. Covers Next.js 16 breaking changes including async params, proxy.ts migration, Cache Components with \"use cache\", and React 19.2 integration. For deploying to Cloudflare Workers, use the cloudflare-nextjs skill instead. This skill is deployment-agnostic and works with Vercel, AWS, self-hosted, or any platform.\n\n  Keywords: Next.js 16, Next.js App Router, Next.js Pages Router, Server Components, React Server Components, Server Actions, Cache Components, use cache, Next.js 16 breaking changes, async params nextjs, proxy.ts migration, React 19.2, Next.js metadata, Next.js SEO, generateMetadata, static generation, dynamic rendering, streaming SSR, Suspense, parallel routes, intercepting routes, route groups, Next.js middleware, Next.js API routes, Route Handlers, revalidatePath, revalidateTag, next\u002Fnavigation, useSearchParams, turbopack, next.config\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  last_verified: 2025-10-24\n  nextjs_version: 16.0.0\n  react_version: 19.2.0\n  node_version: 20.9+\n  author: Jezweb\n  repository: https:\u002F\u002Fgithub.com\u002Fjezweb\u002Fclaude-skills\n  production_tested: true\n  token_savings: 65-70%\n  errors_prevented: 18+\nallowed-tools: [\"Read\", \"Write\", \"Edit\", \"Bash\", \"Glob\", \"Grep\"]\n---\n\n# Next.js App Router - Production Patterns\n\n**Version**: Next.js 16.0.0\n**React Version**: 19.2.0\n**Node.js**: 20.9+\n**Last Verified**: 2025-10-24\n\n---\n\n## Table of Contents\n\n1. [When to Use This Skill](#when-to-use-this-skill)\n2. [When NOT to Use This Skill](#when-not-to-use-this-skill)\n3. [Next.js 16 Breaking Changes](#nextjs-16-breaking-changes)\n4. [Cache Components & Caching APIs](#cache-components--caching-apis)\n5. [Server Components](#server-components)\n6. [Server Actions](#server-actions)\n7. [Route Handlers](#route-handlers)\n8. [Proxy vs Middleware](#proxy-vs-middleware)\n9. [Parallel Routes & Route Groups](#parallel-routes--route-groups)\n10. [React 19.2 Features](#react-192-features)\n11. [Metadata API](#metadata-api)\n12. [Image & Font Optimization](#image--font-optimization)\n13. [Performance Patterns](#performance-patterns)\n14. [TypeScript Configuration](#typescript-configuration)\n15. [Common Errors & Solutions](#common-errors--solutions)\n16. [Templates Reference](#templates-reference)\n17. [Additional Resources](#additional-resources)\n\n---\n\n## When to Use This Skill\n\nUse this skill when you need:\n\n- **Next.js 16 App Router patterns** (layouts, loading, error boundaries, routing)\n- **Server Components** best practices (data fetching, composition, streaming)\n- **Server Actions** patterns (forms, mutations, revalidation, error handling)\n- **Cache Components** with `\"use cache\"` directive (NEW in Next.js 16)\n- **New caching APIs**: `revalidateTag()`, `updateTag()`, `refresh()` (Updated in Next.js 16)\n- **Migration from Next.js 15 to 16** (async params, proxy.ts, parallel routes)\n- **Route Handlers** (API endpoints, webhooks, streaming responses)\n- **Proxy patterns** (`proxy.ts` replaces `middleware.ts` in Next.js 16)\n- **Async route params** (`params`, `searchParams`, `cookies()`, `headers()` now async)\n- **Parallel routes with default.js** (breaking change in Next.js 16)\n- **React 19.2 features** (View Transitions, `useEffectEvent()`, React Compiler)\n- **Metadata API** (SEO, Open Graph, Twitter Cards, sitemaps)\n- **Image optimization** (`next\u002Fimage` with updated defaults in Next.js 16)\n- **Font optimization** (`next\u002Ffont` patterns)\n- **Turbopack configuration** (stable and default in Next.js 16)\n- **Performance optimization** (lazy loading, code splitting, PPR, ISR)\n- **TypeScript configuration** (strict mode, path aliases)\n\n---\n\n## When NOT to Use This Skill\n\nDo NOT use this skill for:\n\n- **Cloudflare Workers deployment** → Use `cloudflare-nextjs` skill instead\n- **Pages Router patterns** → This skill covers App Router ONLY (Pages Router is legacy)\n- **Authentication libraries** → Use `clerk-auth`, `auth-js`, or other auth-specific skills\n- **Database integration** → Use `cloudflare-d1`, `drizzle-orm-d1`, or database-specific skills\n- **UI component libraries** → Use `tailwind-v4-shadcn` skill for Tailwind + shadcn\u002Fui\n- **State management** → Use `zustand-state-management`, `tanstack-query` skills\n- **Form libraries** → Use `react-hook-form-zod` skill\n- **Vercel-specific features** → Refer to Vercel platform documentation\n- **Next.js Enterprise features** (ISR, DPR) → Refer to Next.js Enterprise docs\n- **Deployment configuration** → Use platform-specific deployment skills\n\n**Relationship with Other Skills**:\n- **cloudflare-nextjs**: For deploying Next.js to Cloudflare Workers (use BOTH skills together if deploying to Cloudflare)\n- **tailwind-v4-shadcn**: For Tailwind v4 + shadcn\u002Fui setup (composable with this skill)\n- **clerk-auth**: For Clerk authentication in Next.js (composable with this skill)\n- **auth-js**: For Auth.js (NextAuth) integration (composable with this skill)\n\n---\n\n## Next.js 16 Breaking Changes\n\n**IMPORTANT**: Next.js 16 introduces multiple breaking changes. Read this section carefully if migrating from Next.js 15 or earlier.\n\n### 1. Async Route Parameters (BREAKING)\n\n**Breaking Change**: `params`, `searchParams`, `cookies()`, `headers()`, `draftMode()` are now **async** and must be awaited.\n\n**Before (Next.js 15)**:\n```typescript\n\u002F\u002F ❌ This no longer works in Next.js 16\nexport default function Page({ params, searchParams }: {\n  params: { slug: string }\n  searchParams: { query: string }\n}) {\n  const slug = params.slug \u002F\u002F ❌ Error: params is a Promise\n  const query = searchParams.query \u002F\u002F ❌ Error: searchParams is a Promise\n  return \u003Cdiv>{slug}\u003C\u002Fdiv>\n}\n```\n\n**After (Next.js 16)**:\n```typescript\n\u002F\u002F ✅ Correct: await params and searchParams\nexport default async function Page({ params, searchParams }: {\n  params: Promise\u003C{ slug: string }>\n  searchParams: Promise\u003C{ query: string }>\n}) {\n  const { slug } = await params \u002F\u002F ✅ Await the promise\n  const { query } = await searchParams \u002F\u002F ✅ Await the promise\n  return \u003Cdiv>{slug}\u003C\u002Fdiv>\n}\n```\n\n**Applies to**:\n- `params` in pages, layouts, route handlers\n- `searchParams` in pages\n- `cookies()` from `next\u002Fheaders`\n- `headers()` from `next\u002Fheaders`\n- `draftMode()` from `next\u002Fheaders`\n\n**Migration**:\n```typescript\n\u002F\u002F ❌ Before\nimport { cookies, headers } from 'next\u002Fheaders'\n\nexport function MyComponent() {\n  const cookieStore = cookies() \u002F\u002F ❌ Sync access\n  const headersList = headers() \u002F\u002F ❌ Sync access\n}\n\n\u002F\u002F ✅ After\nimport { cookies, headers } from 'next\u002Fheaders'\n\nexport async function MyComponent() {\n  const cookieStore = await cookies() \u002F\u002F ✅ Async access\n  const headersList = await headers() \u002F\u002F ✅ Async access\n}\n```\n\n**Codemod**: Run `npx @next\u002Fcodemod@canary upgrade latest` to automatically migrate.\n\n**See Template**: `templates\u002Fapp-router-async-params.tsx`\n\n---\n\n### 2. Middleware → Proxy Migration (BREAKING)\n\n**Breaking Change**: `middleware.ts` is **deprecated** in Next.js 16. Use `proxy.ts` instead.\n\n**Why the Change**: `proxy.ts` makes the network boundary explicit by running on Node.js runtime (not Edge runtime). This provides better clarity between edge middleware and server-side proxies.\n\n**Migration Steps**:\n\n1. **Rename file**: `middleware.ts` → `proxy.ts`\n2. **Rename function**: `middleware` → `proxy`\n3. **Update config**: `matcher` → `config.matcher` (same syntax)\n\n**Before (Next.js 15)**:\n```typescript\n\u002F\u002F middleware.ts ❌ Deprecated in Next.js 16\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function middleware(request: NextRequest) {\n  const response = NextResponse.next()\n  response.headers.set('x-custom-header', 'value')\n  return response\n}\n\nexport const config = {\n  matcher: '\u002Fapi\u002F:path*',\n}\n```\n\n**After (Next.js 16)**:\n```typescript\n\u002F\u002F proxy.ts ✅ New in Next.js 16\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function proxy(request: NextRequest) {\n  const response = NextResponse.next()\n  response.headers.set('x-custom-header', 'value')\n  return response\n}\n\nexport const config = {\n  matcher: '\u002Fapi\u002F:path*',\n}\n```\n\n**Note**: `middleware.ts` still works in Next.js 16 but is deprecated. Migrate to `proxy.ts` for future compatibility.\n\n**See Template**: `templates\u002Fproxy-migration.ts`\n**See Reference**: `references\u002Fproxy-vs-middleware.md`\n\n---\n\n### 3. Parallel Routes Require `default.js` (BREAKING)\n\n**Breaking Change**: Parallel routes now **require** explicit `default.js` files. Without them, routes will fail during soft navigation.\n\n**Structure**:\n```\napp\u002F\n├── @auth\u002F\n│   ├── login\u002F\n│   │   └── page.tsx\n│   └── default.tsx    ← REQUIRED in Next.js 16\n├── @dashboard\u002F\n│   ├── overview\u002F\n│   │   └── page.tsx\n│   └── default.tsx    ← REQUIRED in Next.js 16\n└── layout.tsx\n```\n\n**Layout**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nexport default function Layout({\n  children,\n  auth,\n  dashboard,\n}: {\n  children: React.ReactNode\n  auth: React.ReactNode\n  dashboard: React.ReactNode\n}) {\n  return (\n    \u003Chtml>\n      \u003Cbody>\n        {auth}\n        {dashboard}\n        {children}\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Default Fallback** (REQUIRED):\n```typescript\n\u002F\u002F app\u002F@auth\u002Fdefault.tsx\nexport default function AuthDefault() {\n  return null \u002F\u002F or \u003CSkeleton \u002F> or redirect\n}\n\n\u002F\u002F app\u002F@dashboard\u002Fdefault.tsx\nexport default function DashboardDefault() {\n  return null\n}\n```\n\n**Why Required**: Next.js 16 changed how parallel routes handle soft navigation. Without `default.js`, unmatched slots will error during client-side navigation.\n\n**See Template**: `templates\u002Fparallel-routes-with-default.tsx`\n\n---\n\n### 4. Removed Features (BREAKING)\n\n**The following features are REMOVED in Next.js 16**:\n\n1. **AMP Support** - Entirely removed. Migrate to standard pages.\n2. **`next lint` command** - Use ESLint or Biome directly.\n3. **`serverRuntimeConfig` and `publicRuntimeConfig`** - Use environment variables instead.\n4. **`experimental.ppr` flag** - Evolved into Cache Components. Use `\"use cache\"` directive.\n5. **Automatic `scroll-behavior: smooth`** - Add manually if needed.\n6. **Node.js 18 support** - Minimum version is now **20.9+**.\n\n**Migration**:\n- **AMP**: Convert AMP pages to standard pages or use separate AMP implementation.\n- **Linting**: Run `npx eslint .` or `npx biome lint .` directly.\n- **Config**: Replace `serverRuntimeConfig` with `process.env.VARIABLE`.\n- **PPR**: Migrate from `experimental.ppr` to `\"use cache\"` directive (see Cache Components section).\n\n---\n\n### 5. Version Requirements (BREAKING)\n\n**Next.js 16 requires**:\n\n- **Node.js**: 20.9+ (Node.js 18 no longer supported)\n- **TypeScript**: 5.1+ (if using TypeScript)\n- **React**: 19.2+ (automatically installed with Next.js 16)\n- **Browsers**: Chrome 111+, Safari 16.4+, Firefox 109+, Edge 111+\n\n**Check Versions**:\n```bash\nnode --version    # Should be 20.9+\nnpm --version     # Should be 10+\nnpx next --version # Should be 16.0.0+\n```\n\n**Upgrade Node.js**:\n```bash\n# Using nvm\nnvm install 20\nnvm use 20\nnvm alias default 20\n\n# Using Homebrew (macOS)\nbrew install node@20\n\n# Using apt (Ubuntu\u002FDebian)\nsudo apt update\nsudo apt install nodejs npm\n```\n\n---\n\n### 6. Image Defaults Changed (BREAKING)\n\n**Next.js 16 changed `next\u002Fimage` defaults**:\n\n| Setting | Next.js 15 | Next.js 16 |\n|---------|------------|------------|\n| **TTL** (cache duration) | 60 seconds | 4 hours |\n| **imageSizes** | `[16, 32, 48, 64, 96, 128, 256, 384]` | `[640, 750, 828, 1080, 1200]` (reduced) |\n| **qualities** | `[75, 90, 100]` | `[75]` (single quality) |\n\n**Impact**:\n- Images cache longer (4 hours vs 60 seconds)\n- Fewer image sizes generated (smaller builds, but less granular)\n- Single quality (75) generated instead of multiple\n\n**Override Defaults** (if needed):\n```typescript\n\u002F\u002F next.config.ts\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  images: {\n    minimumCacheTTL: 60, \u002F\u002F Revert to 60 seconds\n    deviceSizes: [640, 750, 828, 1080, 1200, 1920], \u002F\u002F Add larger sizes\n    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], \u002F\u002F Restore old sizes\n    formats: ['image\u002Fwebp'], \u002F\u002F Default\n  },\n}\n\nexport default config\n```\n\n**See Template**: `templates\u002Fimage-optimization.tsx`\n\n---\n\n## Cache Components & Caching APIs\n\n**NEW in Next.js 16**: Cache Components introduce **opt-in caching** with the `\"use cache\"` directive, replacing implicit caching from Next.js 15.\n\n### 1. Overview\n\n**What Changed**:\n- **Next.js 15**: Implicit caching (all Server Components cached by default)\n- **Next.js 16**: Opt-in caching with `\"use cache\"` directive\n\n**Why the Change**: Explicit caching gives developers more control and makes caching behavior predictable.\n\n**Cache Components enable**:\n- Component-level caching (cache specific components, not entire pages)\n- Function-level caching (cache expensive computations)\n- Page-level caching (cache entire pages selectively)\n- **Partial Prerendering (PPR)** - Cache static parts, render dynamic parts on-demand\n\n---\n\n### 2. `\"use cache\"` Directive\n\n**Syntax**: Add `\"use cache\"` at the top of a Server Component, function, or route handler.\n\n**Component-level caching**:\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Fexpensive-component.tsx\n'use cache'\n\nexport async function ExpensiveComponent() {\n  const data = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata')\n  const json = await data.json()\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{json.title}\u003C\u002Fh1>\n      \u003Cp>{json.description}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Function-level caching**:\n```typescript\n\u002F\u002F lib\u002Fdata.ts\n'use cache'\n\nexport async function getExpensiveData(id: string) {\n  const response = await fetch(`https:\u002F\u002Fapi.example.com\u002Fitems\u002F${id}`)\n  return response.json()\n}\n\n\u002F\u002F Usage in component\nimport { getExpensiveData } from '@\u002Flib\u002Fdata'\n\nexport async function ProductPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n  const product = await getExpensiveData(id) \u002F\u002F Cached\n\n  return \u003Cdiv>{product.name}\u003C\u002Fdiv>\n}\n```\n\n**Page-level caching**:\n```typescript\n\u002F\u002F app\u002Fblog\u002F[slug]\u002Fpage.tsx\n'use cache'\n\nexport async function generateStaticParams() {\n  const posts = await fetch('https:\u002F\u002Fapi.example.com\u002Fposts').then(r => r.json())\n  return posts.map((post: { slug: string }) => ({ slug: post.slug }))\n}\n\nexport default async function BlogPost({ params }: { params: Promise\u003C{ slug: string }> }) {\n  const { slug } = await params\n  const post = await fetch(`https:\u002F\u002Fapi.example.com\u002Fposts\u002F${slug}`).then(r => r.json())\n\n  return (\n    \u003Carticle>\n      \u003Ch1>{post.title}\u003C\u002Fh1>\n      \u003Cdiv>{post.content}\u003C\u002Fdiv>\n    \u003C\u002Farticle>\n  )\n}\n```\n\n**See Template**: `templates\u002Fcache-component-use-cache.tsx`\n\n---\n\n### 3. Partial Prerendering (PPR)\n\n**PPR** allows caching static parts of a page while rendering dynamic parts on-demand.\n\n**Pattern**:\n```typescript\n\u002F\u002F app\u002Fdashboard\u002Fpage.tsx\n\n\u002F\u002F Static header (cached)\n'use cache'\nasync function StaticHeader() {\n  return \u003Cheader>My App\u003C\u002Fheader>\n}\n\n\u002F\u002F Dynamic user info (not cached)\nasync function DynamicUserInfo() {\n  const cookieStore = await cookies()\n  const userId = cookieStore.get('userId')?.value\n  const user = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(r => r.json())\n\n  return \u003Cdiv>Welcome, {user.name}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Page combines both\nexport default function Dashboard() {\n  return (\n    \u003Cdiv>\n      \u003CStaticHeader \u002F> {\u002F* Cached *\u002F}\n      \u003CDynamicUserInfo \u002F> {\u002F* Dynamic *\u002F}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**When to Use PPR**:\n- Page has both static and dynamic content\n- Want to cache layout\u002Fheader\u002Ffooter but render user-specific content\n- Need fast initial load (static parts) + personalization (dynamic parts)\n\n**See Reference**: `references\u002Fcache-components-guide.md`\n\n---\n\n### 4. `revalidateTag()` - Updated API\n\n**BREAKING CHANGE**: `revalidateTag()` now requires a **second argument** (`cacheLife` profile) for stale-while-revalidate behavior.\n\n**Before (Next.js 15)**:\n```typescript\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function updatePost(id: string) {\n  await fetch(`\u002Fapi\u002Fposts\u002F${id}`, { method: 'PATCH' })\n  revalidateTag('posts') \u002F\u002F ❌ Only one argument in Next.js 15\n}\n```\n\n**After (Next.js 16)**:\n```typescript\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function updatePost(id: string) {\n  await fetch(`\u002Fapi\u002Fposts\u002F${id}`, { method: 'PATCH' })\n  revalidateTag('posts', 'max') \u002F\u002F ✅ Second argument required in Next.js 16\n}\n```\n\n**Built-in Cache Life Profiles**:\n- `'max'` - Maximum staleness (recommended for most use cases)\n- `'hours'` - Stale after hours\n- `'days'` - Stale after days\n- `'weeks'` - Stale after weeks\n- `'default'` - Default cache behavior\n\n**Custom Cache Life Profile**:\n```typescript\nrevalidateTag('posts', {\n  stale: 3600, \u002F\u002F Stale after 1 hour (seconds)\n  revalidate: 86400, \u002F\u002F Revalidate every 24 hours (seconds)\n  expire: false, \u002F\u002F Never expire (optional)\n})\n```\n\n**Pattern in Server Actions**:\n```typescript\n'use server'\n\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function createPost(formData: FormData) {\n  const title = formData.get('title') as string\n  const content = formData.get('content') as string\n\n  await fetch('\u002Fapi\u002Fposts', {\n    method: 'POST',\n    body: JSON.stringify({ title, content }),\n  })\n\n  revalidateTag('posts', 'max') \u002F\u002F ✅ Revalidate with max staleness\n}\n```\n\n**See Template**: `templates\u002Frevalidate-tag-cache-life.ts`\n\n---\n\n### 5. `updateTag()` - NEW API (Server Actions Only)\n\n**NEW in Next.js 16**: `updateTag()` provides **read-your-writes semantics** for Server Actions.\n\n**What it does**:\n- Expires cache immediately\n- Refreshes data within the same request\n- Shows updated data right after mutation (no stale data)\n\n**Difference from `revalidateTag()`**:\n- `revalidateTag()`: **Stale-while-revalidate** (shows stale data, revalidates in background)\n- `updateTag()`: **Immediate refresh** (expires cache, fetches fresh data in same request)\n\n**Use Case**: Forms, user settings, or any mutation where user expects immediate feedback.\n\n**Pattern**:\n```typescript\n'use server'\n\nimport { updateTag } from 'next\u002Fcache'\n\nexport async function updateUserProfile(formData: FormData) {\n  const name = formData.get('name') as string\n  const email = formData.get('email') as string\n\n  \u002F\u002F Update database\n  await db.users.update({ name, email })\n\n  \u002F\u002F Immediately refresh cache (read-your-writes)\n  updateTag('user-profile')\n\n  \u002F\u002F User sees updated data immediately (no stale data)\n}\n```\n\n**When to Use**:\n- **`updateTag()`**: User settings, profile updates, critical mutations (immediate feedback)\n- **`revalidateTag()`**: Blog posts, product listings, non-critical updates (background revalidation)\n\n**See Template**: `templates\u002Fserver-action-update-tag.ts`\n\n---\n\n### 6. `refresh()` - NEW API (Server Actions Only)\n\n**NEW in Next.js 16**: `refresh()` refreshes **uncached data only** (complements client-side `router.refresh()`).\n\n**When to Use**:\n- Refresh dynamic data without affecting cached data\n- Complement `router.refresh()` on server side\n\n**Pattern**:\n```typescript\n'use server'\n\nimport { refresh } from 'next\u002Fcache'\n\nexport async function refreshDashboard() {\n  \u002F\u002F Refresh uncached data (e.g., real-time metrics)\n  refresh()\n\n  \u002F\u002F Cached data (e.g., static header) remains cached\n}\n```\n\n**Difference from `revalidateTag()` and `updateTag()`**:\n- `refresh()`: Only refreshes **uncached** data\n- `revalidateTag()`: Revalidates **specific tagged** data (stale-while-revalidate)\n- `updateTag()`: Immediately expires and refreshes **specific tagged** data\n\n**See Reference**: `references\u002Fcache-components-guide.md`\n\n---\n\n## Server Components\n\nServer Components are React components that render on the server. They enable efficient data fetching, reduce client bundle size, and improve performance.\n\n### 1. Server Component Basics\n\n**Default Behavior**: All components in the App Router are Server Components by default (unless marked with `'use client'`).\n\n**Example**:\n```typescript\n\u002F\u002F app\u002Fposts\u002Fpage.tsx (Server Component by default)\nexport default async function PostsPage() {\n  const posts = await fetch('https:\u002F\u002Fapi.example.com\u002Fposts').then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      {posts.map((post: { id: string; title: string }) => (\n        \u003Carticle key={post.id}>\n          \u003Ch2>{post.title}\u003C\u002Fh2>\n        \u003C\u002Farticle>\n      ))}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Rules**:\n- ✅ Can `await` promises directly in component body\n- ✅ Can access `cookies()`, `headers()`, `draftMode()` (with `await`)\n- ✅ Can use Node.js APIs (fs, path, etc.)\n- ❌ Cannot use browser APIs (window, document, localStorage)\n- ❌ Cannot use React hooks (`useState`, `useEffect`, etc.)\n- ❌ Cannot use event handlers (`onClick`, `onChange`, etc.)\n\n---\n\n### 2. Data Fetching in Server Components\n\n**Pattern**: Use `async\u002Fawait` directly in component body.\n\n```typescript\n\u002F\u002F app\u002Fproducts\u002F[id]\u002Fpage.tsx\nexport default async function ProductPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n\n  \u002F\u002F Fetch data directly in component\n  const product = await fetch(`https:\u002F\u002Fapi.example.com\u002Fproducts\u002F${id}`)\n    .then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{product.name}\u003C\u002Fh1>\n      \u003Cp>{product.description}\u003C\u002Fp>\n      \u003Cp>${product.price}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Parallel Data Fetching**:\n```typescript\nexport default async function Dashboard() {\n  \u002F\u002F Fetch in parallel with Promise.all\n  const [user, posts, comments] = await Promise.all([\n    fetch('\u002Fapi\u002Fuser').then(r => r.json()),\n    fetch('\u002Fapi\u002Fposts').then(r => r.json()),\n    fetch('\u002Fapi\u002Fcomments').then(r => r.json()),\n  ])\n\n  return (\n    \u003Cdiv>\n      \u003CUserInfo user={user} \u002F>\n      \u003CPostsList posts={posts} \u002F>\n      \u003CCommentsList comments={comments} \u002F>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Sequential Data Fetching** (when needed):\n```typescript\nexport default async function UserPosts({ params }: { params: Promise\u003C{ userId: string }> }) {\n  const { userId } = await params\n\n  \u002F\u002F Fetch user first\n  const user = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(r => r.json())\n\n  \u002F\u002F Then fetch user's posts (depends on user data)\n  const posts = await fetch(`\u002Fapi\u002Fposts?userId=${user.id}`).then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{user.name}'s Posts\u003C\u002Fh1>\n      \u003Cul>\n        {posts.map((post: { id: string; title: string }) => (\n          \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n        ))}\n      \u003C\u002Ful>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**See Template**: `templates\u002Fserver-component-streaming.tsx`\n\n---\n\n### 3. Streaming with Suspense\n\n**Pattern**: Wrap slow components in `\u003CSuspense>` to stream content as it loads.\n\n```typescript\nimport { Suspense } from 'react'\n\n\u002F\u002F Fast component (loads immediately)\nasync function Header() {\n  return \u003Cheader>My App\u003C\u002Fheader>\n}\n\n\u002F\u002F Slow component (takes 2 seconds)\nasync function SlowData() {\n  await new Promise(resolve => setTimeout(resolve, 2000))\n  const data = await fetch('\u002Fapi\u002Fslow-data').then(r => r.json())\n  return \u003Cdiv>{data.content}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Page streams content\nexport default function Page() {\n  return (\n    \u003Cdiv>\n      \u003CHeader \u002F> {\u002F* Loads immediately *\u002F}\n\n      \u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n        \u003CSlowData \u002F> {\u002F* Streams when ready *\u002F}\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**When to Use Streaming**:\n- Page has slow API calls\n- Want to show UI immediately (don't wait for all data)\n- Improve perceived performance\n\n**See Reference**: `references\u002Fserver-components-patterns.md`\n\n---\n\n### 4. Server vs Client Components\n\n**When to Use Server Components** (default):\n- Fetch data from APIs\u002Fdatabases\n- Access backend resources (files, environment variables)\n- Keep large dependencies on server (reduce bundle size)\n- Render static content\n\n**When to Use Client Components** (`'use client'`):\n- Need React hooks (`useState`, `useEffect`, `useContext`)\n- Need event handlers (`onClick`, `onChange`, `onSubmit`)\n- Need browser APIs (`window`, `localStorage`, `navigator`)\n- Need third-party libraries that use browser APIs (charts, maps, etc.)\n\n**Pattern**: Use Server Components by default, add `'use client'` only when needed.\n\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Finteractive-button.tsx\n'use client' \u002F\u002F Client Component\n\nimport { useState } from 'react'\n\nexport function InteractiveButton() {\n  const [count, setCount] = useState(0)\n\n  return (\n    \u003Cbutton onClick={() => setCount(count + 1)}>\n      Clicked {count} times\n    \u003C\u002Fbutton>\n  )\n}\n\n\u002F\u002F app\u002Fpage.tsx (Server Component)\nimport { InteractiveButton } from '.\u002Fcomponents\u002Finteractive-button'\n\nexport default async function Page() {\n  const data = await fetch('\u002Fapi\u002Fdata').then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{data.title}\u003C\u002Fh1>\n      \u003CInteractiveButton \u002F> {\u002F* Client Component inside Server Component *\u002F}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Composition Rules**:\n- ✅ Server Component can import Client Component\n- ✅ Client Component can import Client Component\n- ✅ Client Component can render Server Component as children (via props)\n- ❌ Client Component cannot import Server Component directly\n\n**See Reference**: `references\u002Fserver-components-patterns.md`\n\n---\n\n## Server Actions\n\nServer Actions are asynchronous functions that run on the server. They enable server-side mutations, form handling, and data revalidation.\n\n### 1. Server Action Basics\n\n**Definition**: Add `'use server'` directive to create a Server Action.\n\n**File-level Server Actions**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nexport async function createPost(formData: FormData) {\n  const title = formData.get('title') as string\n  const content = formData.get('content') as string\n\n  \u002F\u002F Mutate database\n  await db.posts.create({ title, content })\n\n  \u002F\u002F Revalidate cache\n  revalidateTag('posts', 'max')\n}\n```\n\n**Inline Server Actions**:\n```typescript\n\u002F\u002F app\u002Fposts\u002Fnew\u002Fpage.tsx\nexport default function NewPostPage() {\n  async function createPost(formData: FormData) {\n    'use server'\n\n    const title = formData.get('title') as string\n    const content = formData.get('content') as string\n\n    await db.posts.create({ title, content })\n    revalidateTag('posts', 'max')\n  }\n\n  return (\n    \u003Cform action={createPost}>\n      \u003Cinput name=\"title\" \u002F>\n      \u003Ctextarea name=\"content\" \u002F>\n      \u003Cbutton type=\"submit\">Create Post\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**See Template**: `templates\u002Fserver-actions-form.tsx`\n\n---\n\n### 2. Form Handling\n\n**Basic Form**:\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Fcreate-post-form.tsx\nimport { createPost } from '@\u002Fapp\u002Factions'\n\nexport function CreatePostForm() {\n  return (\n    \u003Cform action={createPost}>\n      \u003Clabel>\n        Title:\n        \u003Cinput type=\"text\" name=\"title\" required \u002F>\n      \u003C\u002Flabel>\n\n      \u003Clabel>\n        Content:\n        \u003Ctextarea name=\"content\" required \u002F>\n      \u003C\u002Flabel>\n\n      \u003Cbutton type=\"submit\">Create Post\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**With Loading State** (useFormStatus):\n```typescript\n'use client'\n\nimport { useFormStatus } from 'react-dom'\nimport { createPost } from '@\u002Fapp\u002Factions'\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus()\n\n  return (\n    \u003Cbutton type=\"submit\" disabled={pending}>\n      {pending ? 'Creating...' : 'Create Post'}\n    \u003C\u002Fbutton>\n  )\n}\n\nexport function CreatePostForm() {\n  return (\n    \u003Cform action={createPost}>\n      \u003Cinput type=\"text\" name=\"title\" required \u002F>\n      \u003Ctextarea name=\"content\" required \u002F>\n      \u003CSubmitButton \u002F>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**With Validation**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nimport { z } from 'zod'\nimport { redirect } from 'next\u002Fnavigation'\n\nconst PostSchema = z.object({\n  title: z.string().min(3, 'Title must be at least 3 characters'),\n  content: z.string().min(10, 'Content must be at least 10 characters'),\n})\n\nexport async function createPost(formData: FormData) {\n  const rawData = {\n    title: formData.get('title'),\n    content: formData.get('content'),\n  }\n\n  \u002F\u002F Validate\n  const parsed = PostSchema.safeParse(rawData)\n\n  if (!parsed.success) {\n    return {\n      errors: parsed.error.flatten().fieldErrors,\n    }\n  }\n\n  \u002F\u002F Mutate\n  await db.posts.create(parsed.data)\n\n  \u002F\u002F Revalidate and redirect\n  revalidateTag('posts', 'max')\n  redirect('\u002Fposts')\n}\n```\n\n**See Template**: `templates\u002Fserver-actions-form.tsx`\n**See Reference**: `references\u002Fserver-actions-guide.md`\n\n---\n\n### 3. Error Handling\n\n**Pattern**: Return error objects from Server Actions, handle in Client Components.\n\n**Server Action**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nexport async function deletePost(id: string) {\n  try {\n    await db.posts.delete({ where: { id } })\n    revalidateTag('posts', 'max')\n    return { success: true }\n  } catch (error) {\n    return {\n      success: false,\n      error: 'Failed to delete post. Please try again.'\n    }\n  }\n}\n```\n\n**Client Component**:\n```typescript\n'use client'\n\nimport { useState } from 'react'\nimport { deletePost } from '@\u002Fapp\u002Factions'\n\nexport function DeleteButton({ postId }: { postId: string }) {\n  const [error, setError] = useState\u003Cstring | null>(null)\n\n  async function handleDelete() {\n    const result = await deletePost(postId)\n\n    if (!result.success) {\n      setError(result.error)\n    }\n  }\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={handleDelete}>Delete Post\u003C\u002Fbutton>\n      {error && \u003Cp className=\"error\">{error}\u003C\u002Fp>}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n---\n\n### 4. Optimistic Updates\n\n**Pattern**: Show UI update immediately, then sync with server.\n\n```typescript\n'use client'\n\nimport { useOptimistic } from 'react'\nimport { likePost } from '@\u002Fapp\u002Factions'\n\nexport function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {\n  const [optimisticLikes, addOptimisticLike] = useOptimistic(\n    initialLikes,\n    (state, amount: number) => state + amount\n  )\n\n  async function handleLike() {\n    \u002F\u002F Update UI immediately\n    addOptimisticLike(1)\n\n    \u002F\u002F Sync with server\n    await likePost(postId)\n  }\n\n  return (\n    \u003Cbutton onClick={handleLike}>\n      ❤️ {optimisticLikes} likes\n    \u003C\u002Fbutton>\n  )\n}\n```\n\n**See Reference**: `references\u002Fserver-actions-guide.md`\n\n---\n\n## Route Handlers\n\nRoute Handlers are server-side API endpoints in the App Router. They replace API Routes from the Pages Router.\n\n### 1. Basic Route Handler\n\n**File**: `app\u002Fapi\u002Fhello\u002Froute.ts`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET() {\n  return NextResponse.json({ message: 'Hello, World!' })\n}\n\nexport async function POST(request: Request) {\n  const body = await request.json()\n\n  return NextResponse.json({\n    message: 'Post created',\n    data: body\n  })\n}\n```\n\n**Supported Methods**: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`\n\n**See Template**: `templates\u002Froute-handler-api.ts`\n\n---\n\n### 2. Dynamic Routes\n\n**File**: `app\u002Fapi\u002Fposts\u002F[id]\u002Froute.ts`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET(\n  request: Request,\n  { params }: { params: Promise\u003C{ id: string }> }\n) {\n  const { id } = await params \u002F\u002F ✅ Await params in Next.js 16\n\n  const post = await db.posts.findUnique({ where: { id } })\n\n  if (!post) {\n    return NextResponse.json(\n      { error: 'Post not found' },\n      { status: 404 }\n    )\n  }\n\n  return NextResponse.json(post)\n}\n\nexport async function DELETE(\n  request: Request,\n  { params }: { params: Promise\u003C{ id: string }> }\n) {\n  const { id } = await params\n\n  await db.posts.delete({ where: { id } })\n\n  return NextResponse.json({ message: 'Post deleted' })\n}\n```\n\n---\n\n### 3. Search Params\n\n**URL**: `\u002Fapi\u002Fposts?tag=javascript&limit=10`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET(request: Request) {\n  const { searchParams } = new URL(request.url)\n  const tag = searchParams.get('tag')\n  const limit = parseInt(searchParams.get('limit') || '10')\n\n  const posts = await db.posts.findMany({\n    where: { tags: { has: tag } },\n    take: limit,\n  })\n\n  return NextResponse.json(posts)\n}\n```\n\n---\n\n### 4. Webhooks\n\n**Pattern**: Handle incoming webhooks from third-party services.\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Fstripe\u002Froute.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport { headers } from 'next\u002Fheaders'\n\nexport async function POST(request: Request) {\n  const body = await request.text()\n  const headersList = await headers() \u002F\u002F ✅ Await headers in Next.js 16\n  const signature = headersList.get('stripe-signature')\n\n  \u002F\u002F Verify webhook signature\n  const event = stripe.webhooks.constructEvent(\n    body,\n    signature!,\n    process.env.STRIPE_WEBHOOK_SECRET!\n  )\n\n  \u002F\u002F Handle event\n  switch (event.type) {\n    case 'payment_intent.succeeded':\n      await handlePaymentSuccess(event.data.object)\n      break\n    case 'payment_intent.failed':\n      await handlePaymentFailure(event.data.object)\n      break\n  }\n\n  return NextResponse.json({ received: true })\n}\n```\n\n**See Template**: `templates\u002Froute-handler-api.ts`\n**See Reference**: `references\u002Froute-handlers-reference.md`\n\n---\n\n## Proxy vs Middleware\n\n**Next.js 16 introduces `proxy.ts`** to replace `middleware.ts`.\n\n### Why the Change?\n\n- **`middleware.ts`**: Runs on Edge runtime (limited Node.js APIs)\n- **`proxy.ts`**: Runs on Node.js runtime (full Node.js APIs)\n\nThe new `proxy.ts` makes the network boundary explicit and provides more flexibility.\n\n### Migration\n\n**Before (middleware.ts)**:\n```typescript\n\u002F\u002F middleware.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function middleware(request: NextRequest) {\n  \u002F\u002F Check auth\n  const token = request.cookies.get('token')\n\n  if (!token) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url))\n  }\n\n  return NextResponse.next()\n}\n\nexport const config = {\n  matcher: '\u002Fdashboard\u002F:path*',\n}\n```\n\n**After (proxy.ts)**:\n```typescript\n\u002F\u002F proxy.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function proxy(request: NextRequest) {\n  \u002F\u002F Check auth\n  const token = request.cookies.get('token')\n\n  if (!token) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url))\n  }\n\n  return NextResponse.next()\n}\n\nexport const config = {\n  matcher: '\u002Fdashboard\u002F:path*',\n}\n```\n\n**See Template**: `templates\u002Fproxy-migration.ts`\n**See Reference**: `references\u002Fproxy-vs-middleware.md`\n\n---\n\n## Parallel Routes & Route Groups\n\n### 1. Parallel Routes\n\n**Use Case**: Render multiple pages in the same layout (e.g., modal + main content, dashboard panels).\n\n**Structure**:\n```\napp\u002F\n├── @modal\u002F\n│   ├── login\u002F\n│   │   └── page.tsx\n│   └── default.tsx  ← REQUIRED in Next.js 16\n├── @feed\u002F\n│   ├── trending\u002F\n│   │   └── page.tsx\n│   └── default.tsx  ← REQUIRED in Next.js 16\n└── layout.tsx\n```\n\n**Layout**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nexport default function Layout({\n  children,\n  modal,\n  feed,\n}: {\n  children: React.ReactNode\n  modal: React.ReactNode\n  feed: React.ReactNode\n}) {\n  return (\n    \u003Chtml>\n      \u003Cbody>\n        {modal}\n        \u003Cmain>\n          {children}\n          \u003Caside>{feed}\u003C\u002Faside>\n        \u003C\u002Fmain>\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Default Files (REQUIRED)**:\n```typescript\n\u002F\u002F app\u002F@modal\u002Fdefault.tsx\nexport default function ModalDefault() {\n  return null\n}\n\n\u002F\u002F app\u002F@feed\u002Fdefault.tsx\nexport default function FeedDefault() {\n  return \u003Cdiv>Default Feed\u003C\u002Fdiv>\n}\n```\n\n**See Template**: `templates\u002Fparallel-routes-with-default.tsx`\n\n---\n\n### 2. Route Groups\n\n**Use Case**: Organize routes without affecting URL structure.\n\n**Structure**:\n```\napp\u002F\n├── (marketing)\u002F\n│   ├── about\u002F\n│   │   └── page.tsx       → \u002Fabout\n│   └── contact\u002F\n│       └── page.tsx       → \u002Fcontact\n├── (shop)\u002F\n│   ├── products\u002F\n│   │   └── page.tsx       → \u002Fproducts\n│   └── cart\u002F\n│       └── page.tsx       → \u002Fcart\n└── layout.tsx\n```\n\n**Different Layouts per Group**:\n```\napp\u002F\n├── (marketing)\u002F\n│   ├── layout.tsx          ← Marketing layout\n│   └── about\u002Fpage.tsx\n├── (shop)\u002F\n│   ├── layout.tsx          ← Shop layout\n│   └── products\u002Fpage.tsx\n└── layout.tsx              ← Root layout\n```\n\n**See Reference**: `references\u002Fapp-router-fundamentals.md`\n\n---\n\n## React 19.2 Features\n\nNext.js 16 integrates React 19.2, which includes new features from React Canary.\n\n### 1. View Transitions\n\n**Use Case**: Smooth animations between page transitions.\n\n```typescript\n'use client'\n\nimport { useRouter } from 'next\u002Fnavigation'\nimport { startTransition } from 'react'\n\nexport function NavigationLink({ href, children }: { href: string; children: React.ReactNode }) {\n  const router = useRouter()\n\n  function handleClick(e: React.MouseEvent) {\n    e.preventDefault()\n\n    \u002F\u002F Wrap navigation in startTransition for View Transitions\n    startTransition(() => {\n      router.push(href)\n    })\n  }\n\n  return \u003Ca href={href} onClick={handleClick}>{children}\u003C\u002Fa>\n}\n```\n\n**With CSS View Transitions API**:\n```css\n\u002F* app\u002Fglobals.css *\u002F\n@view-transition {\n  navigation: auto;\n}\n\n\u002F* Animate elements with view-transition-name *\u002F\n.page-title {\n  view-transition-name: page-title;\n}\n```\n\n**See Template**: `templates\u002Fview-transitions-react-19.tsx`\n\n---\n\n### 2. `useEffectEvent()` (Experimental)\n\n**Use Case**: Extract non-reactive logic from `useEffect`.\n\n```typescript\n'use client'\n\nimport { useEffect, experimental_useEffectEvent as useEffectEvent } from 'react'\n\nexport function ChatRoom({ roomId }: { roomId: string }) {\n  const onConnected = useEffectEvent(() => {\n    console.log('Connected to room:', roomId)\n  })\n\n  useEffect(() => {\n    const connection = connectToRoom(roomId)\n    onConnected() \u002F\u002F Non-reactive callback\n\n    return () => connection.disconnect()\n  }, [roomId]) \u002F\u002F Only re-run when roomId changes\n\n  return \u003Cdiv>Chat Room {roomId}\u003C\u002Fdiv>\n}\n```\n\n**Why Use It**: Prevents unnecessary `useEffect` re-runs when callback dependencies change.\n\n---\n\n### 3. React Compiler (Stable)\n\n**Use Case**: Automatic memoization without `useMemo`, `useCallback`.\n\n**Enable in next.config.ts**:\n```typescript\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  experimental: {\n    reactCompiler: true,\n  },\n}\n\nexport default config\n```\n\n**Install Plugin**:\n```bash\nnpm install babel-plugin-react-compiler\n```\n\n**Example** (no manual memoization needed):\n```typescript\n'use client'\n\nexport function ExpensiveList({ items }: { items: string[] }) {\n  \u002F\u002F React Compiler automatically memoizes this\n  const filteredItems = items.filter(item => item.length > 3)\n\n  return (\n    \u003Cul>\n      {filteredItems.map(item => (\n        \u003Cli key={item}>{item}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  )\n}\n```\n\n**See Reference**: `references\u002Freact-19-integration.md`\n\n---\n\n## Metadata API\n\nThe Metadata API provides type-safe SEO and social sharing metadata.\n\n### 1. Static Metadata\n\n**Pattern**: Export `metadata` object from page or layout.\n\n```typescript\n\u002F\u002F app\u002Fpage.tsx\nimport type { Metadata } from 'next'\n\nexport const metadata: Metadata = {\n  title: 'My App',\n  description: 'Welcome to my app',\n  openGraph: {\n    title: 'My App',\n    description: 'Welcome to my app',\n    images: ['\u002Fog-image.jpg'],\n  },\n  twitter: {\n    card: 'summary_large_image',\n    title: 'My App',\n    description: 'Welcome to my app',\n    images: ['\u002Ftwitter-image.jpg'],\n  },\n}\n\nexport default function Page() {\n  return \u003Ch1>Home\u003C\u002Fh1>\n}\n```\n\n---\n\n### 2. Dynamic Metadata\n\n**Pattern**: Export `generateMetadata` async function.\n\n```typescript\n\u002F\u002F app\u002Fposts\u002F[id]\u002Fpage.tsx\nimport type { Metadata } from 'next'\n\nexport async function generateMetadata({ params }: { params: Promise\u003C{ id: string }> }): Promise\u003CMetadata> {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return {\n    title: post.title,\n    description: post.excerpt,\n    openGraph: {\n      title: post.title,\n      description: post.excerpt,\n      images: [post.coverImage],\n    },\n  }\n}\n\nexport default async function PostPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return \u003Carticle>{post.content}\u003C\u002Farticle>\n}\n```\n\n---\n\n### 3. Sitemap\n\n**File**: `app\u002Fsitemap.ts`\n\n```typescript\nimport type { MetadataRoute } from 'next'\n\nexport default async function sitemap(): Promise\u003CMetadataRoute.Sitemap> {\n  const posts = await fetch('\u002Fapi\u002Fposts').then(r => r.json())\n\n  const postUrls = posts.map((post: { id: string; updatedAt: string }) => ({\n    url: `https:\u002F\u002Fexample.com\u002Fposts\u002F${post.id}`,\n    lastModified: post.updatedAt,\n    changeFrequency: 'weekly' as const,\n    priority: 0.8,\n  }))\n\n  return [\n    {\n      url: 'https:\u002F\u002Fexample.com',\n      lastModified: new Date(),\n      changeFrequency: 'daily',\n      priority: 1,\n    },\n    ...postUrls,\n  ]\n}\n```\n\n**See Template**: `templates\u002Fmetadata-config.ts`\n**See Reference**: `references\u002Fmetadata-api-guide.md`\n\n---\n\n## Image & Font Optimization\n\n### 1. next\u002Fimage\n\n**Basic Usage**:\n```typescript\nimport Image from 'next\u002Fimage'\n\nexport function MyImage() {\n  return (\n    \u003CImage\n      src=\"\u002Fhero.jpg\"\n      alt=\"Hero image\"\n      width={1200}\n      height={600}\n      priority \u002F\u002F Load above the fold\n    \u002F>\n  )\n}\n```\n\n**Responsive Images**:\n```typescript\n\u003CImage\n  src=\"\u002Fhero.jpg\"\n  alt=\"Hero\"\n  fill\n  style={{ objectFit: 'cover' }}\n  sizes=\"(max-width: 768px) 100vw, 50vw\"\n\u002F>\n```\n\n**Remote Images** (configure in next.config.ts):\n```typescript\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  images: {\n    remotePatterns: [\n      {\n        protocol: 'https',\n        hostname: 'cdn.example.com',\n        pathname: '\u002Fimages\u002F**',\n      },\n    ],\n  },\n}\n\nexport default config\n```\n\n**See Template**: `templates\u002Fimage-optimization.tsx`\n\n---\n\n### 2. next\u002Ffont\n\n**Google Fonts**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nimport { Inter, Roboto_Mono } from 'next\u002Ffont\u002Fgoogle'\n\nconst inter = Inter({\n  subsets: ['latin'],\n  display: 'swap',\n  variable: '--font-inter',\n})\n\nconst robotoMono = Roboto_Mono({\n  subsets: ['latin'],\n  display: 'swap',\n  variable: '--font-roboto-mono',\n})\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n  return (\n    \u003Chtml lang=\"en\" className={`${inter.variable} ${robotoMono.variable}`}>\n      \u003Cbody>{children}\u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Local Fonts**:\n```typescript\nimport localFont from 'next\u002Ffont\u002Flocal'\n\nconst myFont = localFont({\n  src: '.\u002Ffonts\u002Fmy-font.woff2',\n  display: 'swap',\n  variable: '--font-my-font',\n})\n```\n\n**See Template**: `templates\u002Ffont-optimization.tsx`\n\n---\n\n## Performance Patterns\n\n### 1. Lazy Loading\n\n**Component Lazy Loading**:\n```typescript\nimport dynamic from 'next\u002Fdynamic'\n\nconst HeavyComponent = dynamic(() => import('.\u002Fheavy-component'), {\n  loading: () => \u003Cdiv>Loading...\u003C\u002Fdiv>,\n  ssr: false, \u002F\u002F Disable SSR for client-only components\n})\n\nexport default function Page() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>My Page\u003C\u002Fh1>\n      \u003CHeavyComponent \u002F>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Conditional Loading**:\n```typescript\n'use client'\n\nimport { useState } from 'react'\nimport dynamic from 'next\u002Fdynamic'\n\nconst Chart = dynamic(() => import('.\u002Fchart'), { ssr: false })\n\nexport function Dashboard() {\n  const [showChart, setShowChart] = useState(false)\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => setShowChart(true)}>Show Chart\u003C\u002Fbutton>\n      {showChart && \u003CChart \u002F>}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n---\n\n### 2. Code Splitting\n\n**Route-level Splitting** (automatic):\n```\napp\u002F\n├── page.tsx       → Bundles: \u002F, shared\n├── about\u002F\n│   └── page.tsx   → Bundles: \u002Fabout, shared\n└── products\u002F\n    └── page.tsx   → Bundles: \u002Fproducts, shared\n```\n\n**Component-level Splitting** (with dynamic import):\n```typescript\nconst Analytics = dynamic(() => import('.\u002Fanalytics'))\nconst Comments = dynamic(() => import('.\u002Fcomments'))\n\nexport default function BlogPost() {\n  return (\n    \u003Carticle>\n      \u003Ch1>Post Title\u003C\u002Fh1>\n      \u003Cp>Content...\u003C\u002Fp>\n      \u003CAnalytics \u002F> {\u002F* Separate bundle *\u002F}\n      \u003CComments \u002F>  {\u002F* Separate bundle *\u002F}\n    \u003C\u002Farticle>\n  )\n}\n```\n\n---\n\n### 3. Turbopack (Stable in Next.js 16)\n\n**Default**: Turbopack is now the default bundler in Next.js 16.\n\n**Metrics**:\n- **2–5× faster production builds**\n- **Up to 10× faster Fast Refresh**\n\n**Opt-out** (if needed):\n```bash\nnpm run build -- --webpack\n```\n\n**Enable File System Caching** (beta):\n```typescript\n\u002F\u002F next.config.ts\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  experimental: {\n    turbopack: {\n      fileSystemCaching: true, \u002F\u002F Beta: Persist cache between runs\n    },\n  },\n}\n\nexport default config\n```\n\n**See Reference**: `references\u002Fperformance-optimization.md`\n\n---\n\n## TypeScript Configuration\n\n### 1. Strict Mode\n\n**Enable strict mode** in `tsconfig.json`:\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"noImplicitOverride\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true\n  }\n}\n```\n\n---\n\n### 2. Path Aliases\n\n**Configure in tsconfig.json**:\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@\u002F*\": [\".\u002Fapp\u002F*\"],\n      \"@\u002Fcomponents\u002F*\": [\".\u002Fapp\u002Fcomponents\u002F*\"],\n      \"@\u002Flib\u002F*\": [\".\u002Flib\u002F*\"],\n      \"@\u002Fstyles\u002F*\": [\".\u002Fstyles\u002F*\"]\n    }\n  }\n}\n```\n\n**Usage**:\n```typescript\n\u002F\u002F Instead of: import { Button } from '..\u002F..\u002F..\u002Fcomponents\u002Fbutton'\nimport { Button } from '@\u002Fcomponents\u002Fbutton'\n```\n\n---\n\n### 3. Type-Safe Routing\n\n**Generate types from routes**:\n```bash\nnpm run build\n```\n\n**Usage**:\n```typescript\nimport { useRouter } from 'next\u002Fnavigation'\n\nconst router = useRouter()\n\n\u002F\u002F Type-safe routing\nrouter.push('\u002Fposts\u002F123') \u002F\u002F ✅ Valid route\nrouter.push('\u002Finvalid')   \u002F\u002F ❌ Type error if route doesn't exist\n```\n\n**See Reference**: `references\u002Ftypescript-configuration.md`\n\n---\n\n## Common Errors & Solutions\n\n### 1. Error: `params` is a Promise\n\n**Error**:\n```\nType 'Promise\u003C{ id: string }>' is not assignable to type '{ id: string }'\n```\n\n**Cause**: Next.js 16 changed `params` to async.\n\n**Solution**: Await `params`:\n```typescript\n\u002F\u002F ❌ Before\nexport default function Page({ params }: { params: { id: string } }) {\n  const id = params.id\n}\n\n\u002F\u002F ✅ After\nexport default async function Page({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n}\n```\n\n---\n\n### 2. Error: `searchParams` is a Promise\n\n**Error**:\n```\nProperty 'query' does not exist on type 'Promise\u003C{ query: string }>'\n```\n\n**Cause**: `searchParams` is now async in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nexport default function Page({ searchParams }: { searchParams: { query: string } }) {\n  const query = searchParams.query\n}\n\n\u002F\u002F ✅ After\nexport default async function Page({ searchParams }: { searchParams: Promise\u003C{ query: string }> }) {\n  const { query } = await searchParams\n}\n```\n\n---\n\n### 3. Error: `cookies()` requires await\n\n**Error**:\n```\n'cookies' implicitly has return type 'any'\n```\n\n**Cause**: `cookies()` is now async in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nimport { cookies } from 'next\u002Fheaders'\n\nexport function MyComponent() {\n  const cookieStore = cookies()\n}\n\n\u002F\u002F ✅ After\nimport { cookies } from 'next\u002Fheaders'\n\nexport async function MyComponent() {\n  const cookieStore = await cookies()\n}\n```\n\n---\n\n### 4. Error: Parallel route missing `default.js`\n\n**Error**:\n```\nError: Parallel route @modal\u002Flogin was matched but no default.js was found\n```\n\n**Cause**: Next.js 16 requires `default.js` for all parallel routes.\n\n**Solution**: Add `default.tsx` files:\n```typescript\n\u002F\u002F app\u002F@modal\u002Fdefault.tsx\nexport default function ModalDefault() {\n  return null\n}\n```\n\n---\n\n### 5. Error: `revalidateTag()` requires 2 arguments\n\n**Error**:\n```\nExpected 2 arguments, but got 1\n```\n\n**Cause**: `revalidateTag()` now requires a `cacheLife` argument in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nrevalidateTag('posts')\n\n\u002F\u002F ✅ After\nrevalidateTag('posts', 'max')\n```\n\n---\n\n### 6. Error: Cannot use React hooks in Server Component\n\n**Error**:\n```\nYou're importing a component that needs useState. It only works in a Client Component\n```\n\n**Cause**: Using React hooks in Server Component.\n\n**Solution**: Add `'use client'` directive:\n```typescript\n\u002F\u002F ✅ Add 'use client' at the top\n'use client'\n\nimport { useState } from 'react'\n\nexport function Counter() {\n  const [count, setCount] = useState(0)\n  return \u003Cbutton onClick={() => setCount(count + 1)}>{count}\u003C\u002Fbutton>\n}\n```\n\n---\n\n### 7. Error: `middleware.ts` is deprecated\n\n**Warning**:\n```\nWarning: middleware.ts is deprecated. Use proxy.ts instead.\n```\n\n**Solution**: Migrate to `proxy.ts`:\n```typescript\n\u002F\u002F Rename: middleware.ts → proxy.ts\n\u002F\u002F Rename function: middleware → proxy\n\nexport function proxy(request: NextRequest) {\n  \u002F\u002F Same logic\n}\n```\n\n---\n\n### 8. Error: Turbopack build failure\n\n**Error**:\n```\nError: Failed to compile with Turbopack\n```\n\n**Cause**: Turbopack is now default in Next.js 16.\n\n**Solution**: Opt out of Turbopack if incompatible:\n```bash\nnpm run build -- --webpack\n```\n\n---\n\n### 9. Error: Invalid `next\u002Fimage` src\n\n**Error**:\n```\nInvalid src prop (https:\u002F\u002Fexample.com\u002Fimage.jpg) on `next\u002Fimage`. Hostname \"example.com\" is not configured under images in your `next.config.js`\n```\n\n**Solution**: Add remote patterns in `next.config.ts`:\n```typescript\nconst config: NextConfig = {\n  images: {\n    remotePatterns: [\n      {\n        protocol: 'https',\n        hostname: 'example.com',\n      },\n    ],\n  },\n}\n```\n\n---\n\n### 10. Error: Cannot import Server Component into Client Component\n\n**Error**:\n```\nYou're importing a Server Component into a Client Component\n```\n\n**Solution**: Pass Server Component as children:\n```typescript\n\u002F\u002F ❌ Wrong\n'use client'\nimport { ServerComponent } from '.\u002Fserver-component' \u002F\u002F Error\n\nexport function ClientComponent() {\n  return \u003CServerComponent \u002F>\n}\n\n\u002F\u002F ✅ Correct\n'use client'\n\nexport function ClientComponent({ children }: { children: React.ReactNode }) {\n  return \u003Cdiv>{children}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Usage\n\u003CClientComponent>\n  \u003CServerComponent \u002F> {\u002F* Pass as children *\u002F}\n\u003C\u002FClientComponent>\n```\n\n---\n\n### 11. Error: `generateStaticParams` not working\n\n**Cause**: `generateStaticParams` only works with static generation (`export const dynamic = 'force-static'`).\n\n**Solution**:\n```typescript\nexport const dynamic = 'force-static'\n\nexport async function generateStaticParams() {\n  const posts = await fetch('\u002Fapi\u002Fposts').then(r => r.json())\n  return posts.map((post: { id: string }) => ({ id: post.id }))\n}\n```\n\n---\n\n### 12. Error: `fetch()` not caching\n\n**Cause**: Next.js 16 uses opt-in caching with `\"use cache\"` directive.\n\n**Solution**: Add `\"use cache\"` to component or function:\n```typescript\n'use cache'\n\nexport async function getPosts() {\n  const response = await fetch('\u002Fapi\u002Fposts')\n  return response.json()\n}\n```\n\n---\n\n### 13. Error: Route collision with Route Groups\n\n**Error**:\n```\nError: Conflicting routes: \u002Fabout and \u002F(marketing)\u002Fabout\n```\n\n**Cause**: Route groups create same URL path.\n\n**Solution**: Ensure route groups don't conflict:\n```\napp\u002F\n├── (marketing)\u002Fabout\u002Fpage.tsx  → \u002Fabout\n└── (shop)\u002Fabout\u002Fpage.tsx       → ERROR: Duplicate \u002Fabout\n\n# Fix: Use different routes\napp\u002F\n├── (marketing)\u002Fabout\u002Fpage.tsx     → \u002Fabout\n└── (shop)\u002Fstore-info\u002Fpage.tsx     → \u002Fstore-info\n```\n\n---\n\n### 14. Error: Metadata not updating\n\n**Cause**: Using dynamic metadata without `generateMetadata()`.\n\n**Solution**: Use `generateMetadata()` for dynamic pages:\n```typescript\nexport async function generateMetadata({ params }: { params: Promise\u003C{ id: string }> }): Promise\u003CMetadata> {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return {\n    title: post.title,\n    description: post.excerpt,\n  }\n}\n```\n\n---\n\n### 15. Error: `next\u002Ffont` font not loading\n\n**Cause**: Font variable not applied to HTML element.\n\n**Solution**: Apply font variable to `\u003Chtml>` or `\u003Cbody>`:\n```typescript\nimport { Inter } from 'next\u002Ffont\u002Fgoogle'\n\nconst inter = Inter({ subsets: ['latin'], variable: '--font-inter' })\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n  return (\n    \u003Chtml className={inter.variable}> {\u002F* ✅ Apply variable *\u002F}\n      \u003Cbody>{children}\u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n---\n\n### 16. Error: Environment variables not available in browser\n\n**Cause**: Server-only env vars are not exposed to browser.\n\n**Solution**: Prefix with `NEXT_PUBLIC_` for client-side access:\n```bash\n# .env\nSECRET_KEY=abc123                  # Server-only\nNEXT_PUBLIC_API_URL=https:\u002F\u002Fapi    # Available in browser\n```\n\n```typescript\n\u002F\u002F Server Component (both work)\nconst secret = process.env.SECRET_KEY\nconst apiUrl = process.env.NEXT_PUBLIC_API_URL\n\n\u002F\u002F Client Component (only public vars work)\nconst apiUrl = process.env.NEXT_PUBLIC_API_URL\n```\n\n---\n\n### 17. Error: Server Action not found\n\n**Error**:\n```\nError: Could not find Server Action\n```\n\n**Cause**: Missing `'use server'` directive.\n\n**Solution**: Add `'use server'`:\n```typescript\n\u002F\u002F ❌ Before\nexport async function createPost(formData: FormData) {\n  await db.posts.create({ ... })\n}\n\n\u002F\u002F ✅ After\n'use server'\n\nexport async function createPost(formData: FormData) {\n  await db.posts.create({ ... })\n}\n```\n\n---\n\n### 18. Error: TypeScript path alias not working\n\n**Cause**: Incorrect `baseUrl` or `paths` in `tsconfig.json`.\n\n**Solution**: Configure correctly:\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@\u002F*\": [\".\u002F*\"],\n      \"@\u002Fcomponents\u002F*\": [\".\u002Fapp\u002Fcomponents\u002F*\"]\n    }\n  }\n}\n```\n\n**See Reference**: `references\u002Ftop-errors.md`\n\n---\n\n## Templates Reference\n\nThe following templates are available in `templates\u002F`:\n\n**App Router Fundamentals**:\n- `app-router-async-params.tsx` - Async params, searchParams patterns (Next.js 16)\n- `parallel-routes-with-default.tsx` - Parallel routes with required default.js\n- `route-groups-example.tsx` - Route groups organization\n\n**Cache Components (Next.js 16)**:\n- `cache-component-use-cache.tsx` - Cache Components with `\"use cache\"`\n- `partial-prerendering.tsx` - PPR with static + dynamic parts\n- `revalidate-tag-cache-life.ts` - Updated `revalidateTag()` API\n- `server-action-update-tag.ts` - `updateTag()` for read-your-writes\n\n**Server Components**:\n- `server-component-data-fetching.tsx` - Data fetching patterns\n- `server-component-streaming.tsx` - Streaming with Suspense\n- `server-component-composition.tsx` - Server + Client component composition\n\n**Server Actions**:\n- `server-actions-form.tsx` - Form handling with Server Actions\n- `server-actions-validation.ts` - Server Action validation with Zod\n- `server-actions-optimistic.tsx` - Optimistic updates\n\n**Route Handlers**:\n- `route-handler-api.ts` - Basic CRUD API\n- `route-handler-webhook.ts` - Webhook handling\n- `route-handler-streaming.ts` - Streaming responses\n\n**Proxy & Middleware**:\n- `proxy-migration.ts` - Migrate from middleware.ts to proxy.ts\n- `proxy-auth.ts` - Auth with proxy.ts\n\n**React 19.2**:\n- `view-transitions-react-19.tsx` - View Transitions API\n- `use-effect-event.tsx` - `useEffectEvent()` pattern\n- `react-compiler-example.tsx` - React Compiler usage\n\n**Metadata**:\n- `metadata-config.ts` - Static and dynamic metadata\n- `sitemap.ts` - Sitemap generation\n- `robots.ts` - robots.txt generation\n\n**Optimization**:\n- `image-optimization.tsx` - next\u002Fimage patterns\n- `font-optimization.tsx` - next\u002Ffont patterns\n- `lazy-loading.tsx` - Dynamic imports and lazy loading\n- `code-splitting.tsx` - Code splitting strategies\n\n**TypeScript**:\n- `typescript-config.json` - Recommended TypeScript configuration\n- `path-aliases.tsx` - Path alias usage\n\n**Configuration**:\n- `next.config.ts` - Full Next.js configuration\n- `package.json` - Recommended dependencies for Next.js 16\n\n---\n\n## Additional Resources\n\n**Bundled References** (in `references\u002F`):\n- `next-16-migration-guide.md` - Complete migration from Next.js 15 to 16\n- `cache-components-guide.md` - Cache Components deep dive\n- `proxy-vs-middleware.md` - Proxy.ts vs middleware.ts comparison\n- `async-route-params.md` - Async params, searchParams, cookies(), headers()\n- `app-router-fundamentals.md` - App Router concepts and patterns\n- `server-components-patterns.md` - Server Components best practices\n- `server-actions-guide.md` - Server Actions patterns and validation\n- `route-handlers-reference.md` - Route Handlers API reference\n- `metadata-api-guide.md` - Metadata API complete guide\n- `performance-optimization.md` - Performance patterns and Turbopack\n- `react-19-integration.md` - React 19.2 features in Next.js\n- `top-errors.md` - 18+ common errors and solutions\n\n**Scripts**:\n- `scripts\u002Fcheck-versions.sh` - Verify Next.js and dependency versions\n\n**External Documentation**:\n- **Next.js 16 Blog**: https:\u002F\u002Fnextjs.org\u002Fblog\u002Fnext-16\n- **Next.js Docs**: https:\u002F\u002Fnextjs.org\u002Fdocs\n- **React Docs**: https:\u002F\u002Freact.dev\n- **Context7 MCP**: Use `\u002Fwebsites\u002Fnextjs` for latest Next.js reference\n\n---\n\n## Version Compatibility\n\n| Package | Minimum Version | Recommended |\n|---------|----------------|-------------|\n| Next.js | 16.0.0 | 16.0.0+ |\n| React | 19.2.0 | 19.2.0+ |\n| Node.js | 20.9.0 | 20.9.0+ |\n| TypeScript | 5.1.0 | 5.7.0+ |\n| Turbopack | (built-in) | Stable |\n\n**Check Versions**:\n```bash\n.\u002Fscripts\u002Fcheck-versions.sh\n```\n\n---\n\n## Token Efficiency\n\n**Estimated Token Savings**: 65-70%\n\n**Without Skill** (manual setup from docs):\n- Read Next.js 16 migration guide: ~5k tokens\n- Read App Router docs: ~8k tokens\n- Read Server Actions docs: ~4k tokens\n- Read Metadata API docs: ~3k tokens\n- Trial-and-error fixes: ~8k tokens\n- **Total**: ~28k tokens\n\n**With Skill**:\n- Load skill: ~8k tokens\n- Use templates: ~2k tokens\n- **Total**: ~10k tokens\n- **Savings**: ~18k tokens (~64%)\n\n**Errors Prevented**: 18+ common mistakes = 100% error prevention\n\n---\n\n## Maintenance\n\n**Last Verified**: 2025-10-24\n**Next Review**: 2026-01-24 (Quarterly)\n**Maintainer**: Jezweb | jeremy@jezweb.net\n**Repository**: https:\u002F\u002Fgithub.com\u002Fjezweb\u002Fclaude-skills\n\n**Update Triggers**:\n- Next.js major\u002Fminor releases\n- React major releases\n- Breaking changes in APIs\n- New Turbopack features\n\n**Version Check**:\n```bash\ncd skills\u002Fnextjs\n.\u002Fscripts\u002Fcheck-versions.sh\n```\n\n---\n\n**End of SKILL.md**\n","# Next.js App Router - Production Patterns\n\n**Version**: Next.js 16.0.0\n**React Version**: 19.2.0\n**Node.js**: 20.9+\n**Last Verified**: 2025-10-24\n\n---\n\n## Table of Contents\n\n1. [When to Use This Skill](#when-to-use-this-skill)\n2. [When NOT to Use This Skill](#when-not-to-use-this-skill)\n3. [Next.js 16 Breaking Changes](#nextjs-16-breaking-changes)\n4. [Cache Components & Caching APIs](#cache-components--caching-apis)\n5. [Server Components](#server-components)\n6. [Server Actions](#server-actions)\n7. [Route Handlers](#route-handlers)\n8. [Proxy vs Middleware](#proxy-vs-middleware)\n9. [Parallel Routes & Route Groups](#parallel-routes--route-groups)\n10. [React 19.2 Features](#react-192-features)\n11. [Metadata API](#metadata-api)\n12. [Image & Font Optimization](#image--font-optimization)\n13. [Performance Patterns](#performance-patterns)\n14. [TypeScript Configuration](#typescript-configuration)\n15. [Common Errors & Solutions](#common-errors--solutions)\n16. [Templates Reference](#templates-reference)\n17. [Additional Resources](#additional-resources)\n\n---\n\n## When to Use This Skill\n\nUse this skill when you need:\n\n- **Next.js 16 App Router patterns** (layouts, loading, error boundaries, routing)\n- **Server Components** best practices (data fetching, composition, streaming)\n- **Server Actions** patterns (forms, mutations, revalidation, error handling)\n- **Cache Components** with `\"use cache\"` directive (NEW in Next.js 16)\n- **New caching APIs**: `revalidateTag()`, `updateTag()`, `refresh()` (Updated in Next.js 16)\n- **Migration from Next.js 15 to 16** (async params, proxy.ts, parallel routes)\n- **Route Handlers** (API endpoints, webhooks, streaming responses)\n- **Proxy patterns** (`proxy.ts` replaces `middleware.ts` in Next.js 16)\n- **Async route params** (`params`, `searchParams`, `cookies()`, `headers()` now async)\n- **Parallel routes with default.js** (breaking change in Next.js 16)\n- **React 19.2 features** (View Transitions, `useEffectEvent()`, React Compiler)\n- **Metadata API** (SEO, Open Graph, Twitter Cards, sitemaps)\n- **Image optimization** (`next\u002Fimage` with updated defaults in Next.js 16)\n- **Font optimization** (`next\u002Ffont` patterns)\n- **Turbopack configuration** (stable and default in Next.js 16)\n- **Performance optimization** (lazy loading, code splitting, PPR, ISR)\n- **TypeScript configuration** (strict mode, path aliases)\n\n---\n\n## When NOT to Use This Skill\n\nDo NOT use this skill for:\n\n- **Cloudflare Workers deployment** → Use `cloudflare-nextjs` skill instead\n- **Pages Router patterns** → This skill covers App Router ONLY (Pages Router is legacy)\n- **Authentication libraries** → Use `clerk-auth`, `auth-js`, or other auth-specific skills\n- **Database integration** → Use `cloudflare-d1`, `drizzle-orm-d1`, or database-specific skills\n- **UI component libraries** → Use `tailwind-v4-shadcn` skill for Tailwind + shadcn\u002Fui\n- **State management** → Use `zustand-state-management`, `tanstack-query` skills\n- **Form libraries** → Use `react-hook-form-zod` skill\n- **Vercel-specific features** → Refer to Vercel platform documentation\n- **Next.js Enterprise features** (ISR, DPR) → Refer to Next.js Enterprise docs\n- **Deployment configuration** → Use platform-specific deployment skills\n\n**Relationship with Other Skills**:\n- **cloudflare-nextjs**: For deploying Next.js to Cloudflare Workers (use BOTH skills together if deploying to Cloudflare)\n- **tailwind-v4-shadcn**: For Tailwind v4 + shadcn\u002Fui setup (composable with this skill)\n- **clerk-auth**: For Clerk authentication in Next.js (composable with this skill)\n- **auth-js**: For Auth.js (NextAuth) integration (composable with this skill)\n\n---\n\n## Next.js 16 Breaking Changes\n\n**IMPORTANT**: Next.js 16 introduces multiple breaking changes. Read this section carefully if migrating from Next.js 15 or earlier.\n\n### 1. Async Route Parameters (BREAKING)\n\n**Breaking Change**: `params`, `searchParams`, `cookies()`, `headers()`, `draftMode()` are now **async** and must be awaited.\n\n**Before (Next.js 15)**:\n```typescript\n\u002F\u002F ❌ This no longer works in Next.js 16\nexport default function Page({ params, searchParams }: {\n  params: { slug: string }\n  searchParams: { query: string }\n}) {\n  const slug = params.slug \u002F\u002F ❌ Error: params is a Promise\n  const query = searchParams.query \u002F\u002F ❌ Error: searchParams is a Promise\n  return \u003Cdiv>{slug}\u003C\u002Fdiv>\n}\n```\n\n**After (Next.js 16)**:\n```typescript\n\u002F\u002F ✅ Correct: await params and searchParams\nexport default async function Page({ params, searchParams }: {\n  params: Promise\u003C{ slug: string }>\n  searchParams: Promise\u003C{ query: string }>\n}) {\n  const { slug } = await params \u002F\u002F ✅ Await the promise\n  const { query } = await searchParams \u002F\u002F ✅ Await the promise\n  return \u003Cdiv>{slug}\u003C\u002Fdiv>\n}\n```\n\n**Applies to**:\n- `params` in pages, layouts, route handlers\n- `searchParams` in pages\n- `cookies()` from `next\u002Fheaders`\n- `headers()` from `next\u002Fheaders`\n- `draftMode()` from `next\u002Fheaders`\n\n**Migration**:\n```typescript\n\u002F\u002F ❌ Before\nimport { cookies, headers } from 'next\u002Fheaders'\n\nexport function MyComponent() {\n  const cookieStore = cookies() \u002F\u002F ❌ Sync access\n  const headersList = headers() \u002F\u002F ❌ Sync access\n}\n\n\u002F\u002F ✅ After\nimport { cookies, headers } from 'next\u002Fheaders'\n\nexport async function MyComponent() {\n  const cookieStore = await cookies() \u002F\u002F ✅ Async access\n  const headersList = await headers() \u002F\u002F ✅ Async access\n}\n```\n\n**Codemod**: Run `npx @next\u002Fcodemod@canary upgrade latest` to automatically migrate.\n\n**See Template**: `templates\u002Fapp-router-async-params.tsx`\n\n---\n\n### 2. Middleware → Proxy Migration (BREAKING)\n\n**Breaking Change**: `middleware.ts` is **deprecated** in Next.js 16. Use `proxy.ts` instead.\n\n**Why the Change**: `proxy.ts` makes the network boundary explicit by running on Node.js runtime (not Edge runtime). This provides better clarity between edge middleware and server-side proxies.\n\n**Migration Steps**:\n\n1. **Rename file**: `middleware.ts` → `proxy.ts`\n2. **Rename function**: `middleware` → `proxy`\n3. **Update config**: `matcher` → `config.matcher` (same syntax)\n\n**Before (Next.js 15)**:\n```typescript\n\u002F\u002F middleware.ts ❌ Deprecated in Next.js 16\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function middleware(request: NextRequest) {\n  const response = NextResponse.next()\n  response.headers.set('x-custom-header', 'value')\n  return response\n}\n\nexport const config = {\n  matcher: '\u002Fapi\u002F:path*',\n}\n```\n\n**After (Next.js 16)**:\n```typescript\n\u002F\u002F proxy.ts ✅ New in Next.js 16\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function proxy(request: NextRequest) {\n  const response = NextResponse.next()\n  response.headers.set('x-custom-header', 'value')\n  return response\n}\n\nexport const config = {\n  matcher: '\u002Fapi\u002F:path*',\n}\n```\n\n**Note**: `middleware.ts` still works in Next.js 16 but is deprecated. Migrate to `proxy.ts` for future compatibility.\n\n**See Template**: `templates\u002Fproxy-migration.ts`\n**See Reference**: `references\u002Fproxy-vs-middleware.md`\n\n---\n\n### 3. Parallel Routes Require `default.js` (BREAKING)\n\n**Breaking Change**: Parallel routes now **require** explicit `default.js` files. Without them, routes will fail during soft navigation.\n\n**Structure**:\n```\napp\u002F\n├── @auth\u002F\n│   ├── login\u002F\n│   │   └── page.tsx\n│   └── default.tsx    ← REQUIRED in Next.js 16\n├── @dashboard\u002F\n│   ├── overview\u002F\n│   │   └── page.tsx\n│   └── default.tsx    ← REQUIRED in Next.js 16\n└── layout.tsx\n```\n\n**Layout**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nexport default function Layout({\n  children,\n  auth,\n  dashboard,\n}: {\n  children: React.ReactNode\n  auth: React.ReactNode\n  dashboard: React.ReactNode\n}) {\n  return (\n    \u003Chtml>\n      \u003Cbody>\n        {auth}\n        {dashboard}\n        {children}\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Default Fallback** (REQUIRED):\n```typescript\n\u002F\u002F app\u002F@auth\u002Fdefault.tsx\nexport default function AuthDefault() {\n  return null \u002F\u002F or \u003CSkeleton \u002F> or redirect\n}\n\n\u002F\u002F app\u002F@dashboard\u002Fdefault.tsx\nexport default function DashboardDefault() {\n  return null\n}\n```\n\n**Why Required**: Next.js 16 changed how parallel routes handle soft navigation. Without `default.js`, unmatched slots will error during client-side navigation.\n\n**See Template**: `templates\u002Fparallel-routes-with-default.tsx`\n\n---\n\n### 4. Removed Features (BREAKING)\n\n**The following features are REMOVED in Next.js 16**:\n\n1. **AMP Support** - Entirely removed. Migrate to standard pages.\n2. **`next lint` command** - Use ESLint or Biome directly.\n3. **`serverRuntimeConfig` and `publicRuntimeConfig`** - Use environment variables instead.\n4. **`experimental.ppr` flag** - Evolved into Cache Components. Use `\"use cache\"` directive.\n5. **Automatic `scroll-behavior: smooth`** - Add manually if needed.\n6. **Node.js 18 support** - Minimum version is now **20.9+**.\n\n**Migration**:\n- **AMP**: Convert AMP pages to standard pages or use separate AMP implementation.\n- **Linting**: Run `npx eslint .` or `npx biome lint .` directly.\n- **Config**: Replace `serverRuntimeConfig` with `process.env.VARIABLE`.\n- **PPR**: Migrate from `experimental.ppr` to `\"use cache\"` directive (see Cache Components section).\n\n---\n\n### 5. Version Requirements (BREAKING)\n\n**Next.js 16 requires**:\n\n- **Node.js**: 20.9+ (Node.js 18 no longer supported)\n- **TypeScript**: 5.1+ (if using TypeScript)\n- **React**: 19.2+ (automatically installed with Next.js 16)\n- **Browsers**: Chrome 111+, Safari 16.4+, Firefox 109+, Edge 111+\n\n**Check Versions**:\n```bash\nnode --version    # Should be 20.9+\nnpm --version     # Should be 10+\nnpx next --version # Should be 16.0.0+\n```\n\n**Upgrade Node.js**:\n```bash\n# Using nvm\nnvm install 20\nnvm use 20\nnvm alias default 20\n\n# Using Homebrew (macOS)\nbrew install node@20\n\n# Using apt (Ubuntu\u002FDebian)\nsudo apt update\nsudo apt install nodejs npm\n```\n\n---\n\n### 6. Image Defaults Changed (BREAKING)\n\n**Next.js 16 changed `next\u002Fimage` defaults**:\n\n| Setting | Next.js 15 | Next.js 16 |\n|---------|------------|------------|\n| **TTL** (cache duration) | 60 seconds | 4 hours |\n| **imageSizes** | `[16, 32, 48, 64, 96, 128, 256, 384]` | `[640, 750, 828, 1080, 1200]` (reduced) |\n| **qualities** | `[75, 90, 100]` | `[75]` (single quality) |\n\n**Impact**:\n- Images cache longer (4 hours vs 60 seconds)\n- Fewer image sizes generated (smaller builds, but less granular)\n- Single quality (75) generated instead of multiple\n\n**Override Defaults** (if needed):\n```typescript\n\u002F\u002F next.config.ts\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  images: {\n    minimumCacheTTL: 60, \u002F\u002F Revert to 60 seconds\n    deviceSizes: [640, 750, 828, 1080, 1200, 1920], \u002F\u002F Add larger sizes\n    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384], \u002F\u002F Restore old sizes\n    formats: ['image\u002Fwebp'], \u002F\u002F Default\n  },\n}\n\nexport default config\n```\n\n**See Template**: `templates\u002Fimage-optimization.tsx`\n\n---\n\n## Cache Components & Caching APIs\n\n**NEW in Next.js 16**: Cache Components introduce **opt-in caching** with the `\"use cache\"` directive, replacing implicit caching from Next.js 15.\n\n### 1. Overview\n\n**What Changed**:\n- **Next.js 15**: Implicit caching (all Server Components cached by default)\n- **Next.js 16**: Opt-in caching with `\"use cache\"` directive\n\n**Why the Change**: Explicit caching gives developers more control and makes caching behavior predictable.\n\n**Cache Components enable**:\n- Component-level caching (cache specific components, not entire pages)\n- Function-level caching (cache expensive computations)\n- Page-level caching (cache entire pages selectively)\n- **Partial Prerendering (PPR)** - Cache static parts, render dynamic parts on-demand\n\n---\n\n### 2. `\"use cache\"` Directive\n\n**Syntax**: Add `\"use cache\"` at the top of a Server Component, function, or route handler.\n\n**Component-level caching**:\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Fexpensive-component.tsx\n'use cache'\n\nexport async function ExpensiveComponent() {\n  const data = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata')\n  const json = await data.json()\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{json.title}\u003C\u002Fh1>\n      \u003Cp>{json.description}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Function-level caching**:\n```typescript\n\u002F\u002F lib\u002Fdata.ts\n'use cache'\n\nexport async function getExpensiveData(id: string) {\n  const response = await fetch(`https:\u002F\u002Fapi.example.com\u002Fitems\u002F${id}`)\n  return response.json()\n}\n\n\u002F\u002F Usage in component\nimport { getExpensiveData } from '@\u002Flib\u002Fdata'\n\nexport async function ProductPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n  const product = await getExpensiveData(id) \u002F\u002F Cached\n\n  return \u003Cdiv>{product.name}\u003C\u002Fdiv>\n}\n```\n\n**Page-level caching**:\n```typescript\n\u002F\u002F app\u002Fblog\u002F[slug]\u002Fpage.tsx\n'use cache'\n\nexport async function generateStaticParams() {\n  const posts = await fetch('https:\u002F\u002Fapi.example.com\u002Fposts').then(r => r.json())\n  return posts.map((post: { slug: string }) => ({ slug: post.slug }))\n}\n\nexport default async function BlogPost({ params }: { params: Promise\u003C{ slug: string }> }) {\n  const { slug } = await params\n  const post = await fetch(`https:\u002F\u002Fapi.example.com\u002Fposts\u002F${slug}`).then(r => r.json())\n\n  return (\n    \u003Carticle>\n      \u003Ch1>{post.title}\u003C\u002Fh1>\n      \u003Cdiv>{post.content}\u003C\u002Fdiv>\n    \u003C\u002Farticle>\n  )\n}\n```\n\n**See Template**: `templates\u002Fcache-component-use-cache.tsx`\n\n---\n\n### 3. Partial Prerendering (PPR)\n\n**PPR** allows caching static parts of a page while rendering dynamic parts on-demand.\n\n**Pattern**:\n```typescript\n\u002F\u002F app\u002Fdashboard\u002Fpage.tsx\n\n\u002F\u002F Static header (cached)\n'use cache'\nasync function StaticHeader() {\n  return \u003Cheader>My App\u003C\u002Fheader>\n}\n\n\u002F\u002F Dynamic user info (not cached)\nasync function DynamicUserInfo() {\n  const cookieStore = await cookies()\n  const userId = cookieStore.get('userId')?.value\n  const user = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(r => r.json())\n\n  return \u003Cdiv>Welcome, {user.name}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Page combines both\nexport default function Dashboard() {\n  return (\n    \u003Cdiv>\n      \u003CStaticHeader \u002F> {\u002F* Cached *\u002F}\n      \u003CDynamicUserInfo \u002F> {\u002F* Dynamic *\u002F}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**When to Use PPR**:\n- Page has both static and dynamic content\n- Want to cache layout\u002Fheader\u002Ffooter but render user-specific content\n- Need fast initial load (static parts) + personalization (dynamic parts)\n\n**See Reference**: `references\u002Fcache-components-guide.md`\n\n---\n\n### 4. `revalidateTag()` - Updated API\n\n**BREAKING CHANGE**: `revalidateTag()` now requires a **second argument** (`cacheLife` profile) for stale-while-revalidate behavior.\n\n**Before (Next.js 15)**:\n```typescript\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function updatePost(id: string) {\n  await fetch(`\u002Fapi\u002Fposts\u002F${id}`, { method: 'PATCH' })\n  revalidateTag('posts') \u002F\u002F ❌ Only one argument in Next.js 15\n}\n```\n\n**After (Next.js 16)**:\n```typescript\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function updatePost(id: string) {\n  await fetch(`\u002Fapi\u002Fposts\u002F${id}`, { method: 'PATCH' })\n  revalidateTag('posts', 'max') \u002F\u002F ✅ Second argument required in Next.js 16\n}\n```\n\n**Built-in Cache Life Profiles**:\n- `'max'` - Maximum staleness (recommended for most use cases)\n- `'hours'` - Stale after hours\n- `'days'` - Stale after days\n- `'weeks'` - Stale after weeks\n- `'default'` - Default cache behavior\n\n**Custom Cache Life Profile**:\n```typescript\nrevalidateTag('posts', {\n  stale: 3600, \u002F\u002F Stale after 1 hour (seconds)\n  revalidate: 86400, \u002F\u002F Revalidate every 24 hours (seconds)\n  expire: false, \u002F\u002F Never expire (optional)\n})\n```\n\n**Pattern in Server Actions**:\n```typescript\n'use server'\n\nimport { revalidateTag } from 'next\u002Fcache'\n\nexport async function createPost(formData: FormData) {\n  const title = formData.get('title') as string\n  const content = formData.get('content') as string\n\n  await fetch('\u002Fapi\u002Fposts', {\n    method: 'POST',\n    body: JSON.stringify({ title, content }),\n  })\n\n  revalidateTag('posts', 'max') \u002F\u002F ✅ Revalidate with max staleness\n}\n```\n\n**See Template**: `templates\u002Frevalidate-tag-cache-life.ts`\n\n---\n\n### 5. `updateTag()` - NEW API (Server Actions Only)\n\n**NEW in Next.js 16**: `updateTag()` provides **read-your-writes semantics** for Server Actions.\n\n**What it does**:\n- Expires cache immediately\n- Refreshes data within the same request\n- Shows updated data right after mutation (no stale data)\n\n**Difference from `revalidateTag()`**:\n- `revalidateTag()`: **Stale-while-revalidate** (shows stale data, revalidates in background)\n- `updateTag()`: **Immediate refresh** (expires cache, fetches fresh data in same request)\n\n**Use Case**: Forms, user settings, or any mutation where user expects immediate feedback.\n\n**Pattern**:\n```typescript\n'use server'\n\nimport { updateTag } from 'next\u002Fcache'\n\nexport async function updateUserProfile(formData: FormData) {\n  const name = formData.get('name') as string\n  const email = formData.get('email') as string\n\n  \u002F\u002F Update database\n  await db.users.update({ name, email })\n\n  \u002F\u002F Immediately refresh cache (read-your-writes)\n  updateTag('user-profile')\n\n  \u002F\u002F User sees updated data immediately (no stale data)\n}\n```\n\n**When to Use**:\n- **`updateTag()`**: User settings, profile updates, critical mutations (immediate feedback)\n- **`revalidateTag()`**: Blog posts, product listings, non-critical updates (background revalidation)\n\n**See Template**: `templates\u002Fserver-action-update-tag.ts`\n\n---\n\n### 6. `refresh()` - NEW API (Server Actions Only)\n\n**NEW in Next.js 16**: `refresh()` refreshes **uncached data only** (complements client-side `router.refresh()`).\n\n**When to Use**:\n- Refresh dynamic data without affecting cached data\n- Complement `router.refresh()` on server side\n\n**Pattern**:\n```typescript\n'use server'\n\nimport { refresh } from 'next\u002Fcache'\n\nexport async function refreshDashboard() {\n  \u002F\u002F Refresh uncached data (e.g., real-time metrics)\n  refresh()\n\n  \u002F\u002F Cached data (e.g., static header) remains cached\n}\n```\n\n**Difference from `revalidateTag()` and `updateTag()`**:\n- `refresh()`: Only refreshes **uncached** data\n- `revalidateTag()`: Revalidates **specific tagged** data (stale-while-revalidate)\n- `updateTag()`: Immediately expires and refreshes **specific tagged** data\n\n**See Reference**: `references\u002Fcache-components-guide.md`\n\n---\n\n## Server Components\n\nServer Components are React components that render on the server. They enable efficient data fetching, reduce client bundle size, and improve performance.\n\n### 1. Server Component Basics\n\n**Default Behavior**: All components in the App Router are Server Components by default (unless marked with `'use client'`).\n\n**Example**:\n```typescript\n\u002F\u002F app\u002Fposts\u002Fpage.tsx (Server Component by default)\nexport default async function PostsPage() {\n  const posts = await fetch('https:\u002F\u002Fapi.example.com\u002Fposts').then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      {posts.map((post: { id: string; title: string }) => (\n        \u003Carticle key={post.id}>\n          \u003Ch2>{post.title}\u003C\u002Fh2>\n        \u003C\u002Farticle>\n      ))}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Rules**:\n- ✅ Can `await` promises directly in component body\n- ✅ Can access `cookies()`, `headers()`, `draftMode()` (with `await`)\n- ✅ Can use Node.js APIs (fs, path, etc.)\n- ❌ Cannot use browser APIs (window, document, localStorage)\n- ❌ Cannot use React hooks (`useState`, `useEffect`, etc.)\n- ❌ Cannot use event handlers (`onClick`, `onChange`, etc.)\n\n---\n\n### 2. Data Fetching in Server Components\n\n**Pattern**: Use `async\u002Fawait` directly in component body.\n\n```typescript\n\u002F\u002F app\u002Fproducts\u002F[id]\u002Fpage.tsx\nexport default async function ProductPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n\n  \u002F\u002F Fetch data directly in component\n  const product = await fetch(`https:\u002F\u002Fapi.example.com\u002Fproducts\u002F${id}`)\n    .then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{product.name}\u003C\u002Fh1>\n      \u003Cp>{product.description}\u003C\u002Fp>\n      \u003Cp>${product.price}\u003C\u002Fp>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Parallel Data Fetching**:\n```typescript\nexport default async function Dashboard() {\n  \u002F\u002F Fetch in parallel with Promise.all\n  const [user, posts, comments] = await Promise.all([\n    fetch('\u002Fapi\u002Fuser').then(r => r.json()),\n    fetch('\u002Fapi\u002Fposts').then(r => r.json()),\n    fetch('\u002Fapi\u002Fcomments').then(r => r.json()),\n  ])\n\n  return (\n    \u003Cdiv>\n      \u003CUserInfo user={user} \u002F>\n      \u003CPostsList posts={posts} \u002F>\n      \u003CCommentsList comments={comments} \u002F>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Sequential Data Fetching** (when needed):\n```typescript\nexport default async function UserPosts({ params }: { params: Promise\u003C{ userId: string }> }) {\n  const { userId } = await params\n\n  \u002F\u002F Fetch user first\n  const user = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`).then(r => r.json())\n\n  \u002F\u002F Then fetch user's posts (depends on user data)\n  const posts = await fetch(`\u002Fapi\u002Fposts?userId=${user.id}`).then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{user.name}'s Posts\u003C\u002Fh1>\n      \u003Cul>\n        {posts.map((post: { id: string; title: string }) => (\n          \u003Cli key={post.id}>{post.title}\u003C\u002Fli>\n        ))}\n      \u003C\u002Ful>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**See Template**: `templates\u002Fserver-component-streaming.tsx`\n\n---\n\n### 3. Streaming with Suspense\n\n**Pattern**: Wrap slow components in `\u003CSuspense>` to stream content as it loads.\n\n```typescript\nimport { Suspense } from 'react'\n\n\u002F\u002F Fast component (loads immediately)\nasync function Header() {\n  return \u003Cheader>My App\u003C\u002Fheader>\n}\n\n\u002F\u002F Slow component (takes 2 seconds)\nasync function SlowData() {\n  await new Promise(resolve => setTimeout(resolve, 2000))\n  const data = await fetch('\u002Fapi\u002Fslow-data').then(r => r.json())\n  return \u003Cdiv>{data.content}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Page streams content\nexport default function Page() {\n  return (\n    \u003Cdiv>\n      \u003CHeader \u002F> {\u002F* Loads immediately *\u002F}\n\n      \u003CSuspense fallback={\u003Cdiv>Loading...\u003C\u002Fdiv>}>\n        \u003CSlowData \u002F> {\u002F* Streams when ready *\u002F}\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**When to Use Streaming**:\n- Page has slow API calls\n- Want to show UI immediately (don't wait for all data)\n- Improve perceived performance\n\n**See Reference**: `references\u002Fserver-components-patterns.md`\n\n---\n\n### 4. Server vs Client Components\n\n**When to Use Server Components** (default):\n- Fetch data from APIs\u002Fdatabases\n- Access backend resources (files, environment variables)\n- Keep large dependencies on server (reduce bundle size)\n- Render static content\n\n**When to Use Client Components** (`'use client'`):\n- Need React hooks (`useState`, `useEffect`, `useContext`)\n- Need event handlers (`onClick`, `onChange`, `onSubmit`)\n- Need browser APIs (`window`, `localStorage`, `navigator`)\n- Need third-party libraries that use browser APIs (charts, maps, etc.)\n\n**Pattern**: Use Server Components by default, add `'use client'` only when needed.\n\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Finteractive-button.tsx\n'use client' \u002F\u002F Client Component\n\nimport { useState } from 'react'\n\nexport function InteractiveButton() {\n  const [count, setCount] = useState(0)\n\n  return (\n    \u003Cbutton onClick={() => setCount(count + 1)}>\n      Clicked {count} times\n    \u003C\u002Fbutton>\n  )\n}\n\n\u002F\u002F app\u002Fpage.tsx (Server Component)\nimport { InteractiveButton } from '.\u002Fcomponents\u002Finteractive-button'\n\nexport default async function Page() {\n  const data = await fetch('\u002Fapi\u002Fdata').then(r => r.json())\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>{data.title}\u003C\u002Fh1>\n      \u003CInteractiveButton \u002F> {\u002F* Client Component inside Server Component *\u002F}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Composition Rules**:\n- ✅ Server Component can import Client Component\n- ✅ Client Component can import Client Component\n- ✅ Client Component can render Server Component as children (via props)\n- ❌ Client Component cannot import Server Component directly\n\n**See Reference**: `references\u002Fserver-components-patterns.md`\n\n---\n\n## Server Actions\n\nServer Actions are asynchronous functions that run on the server. They enable server-side mutations, form handling, and data revalidation.\n\n### 1. Server Action Basics\n\n**Definition**: Add `'use server'` directive to create a Server Action.\n\n**File-level Server Actions**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nexport async function createPost(formData: FormData) {\n  const title = formData.get('title') as string\n  const content = formData.get('content') as string\n\n  \u002F\u002F Mutate database\n  await db.posts.create({ title, content })\n\n  \u002F\u002F Revalidate cache\n  revalidateTag('posts', 'max')\n}\n```\n\n**Inline Server Actions**:\n```typescript\n\u002F\u002F app\u002Fposts\u002Fnew\u002Fpage.tsx\nexport default function NewPostPage() {\n  async function createPost(formData: FormData) {\n    'use server'\n\n    const title = formData.get('title') as string\n    const content = formData.get('content') as string\n\n    await db.posts.create({ title, content })\n    revalidateTag('posts', 'max')\n  }\n\n  return (\n    \u003Cform action={createPost}>\n      \u003Cinput name=\"title\" \u002F>\n      \u003Ctextarea name=\"content\" \u002F>\n      \u003Cbutton type=\"submit\">Create Post\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**See Template**: `templates\u002Fserver-actions-form.tsx`\n\n---\n\n### 2. Form Handling\n\n**Basic Form**:\n```typescript\n\u002F\u002F app\u002Fcomponents\u002Fcreate-post-form.tsx\nimport { createPost } from '@\u002Fapp\u002Factions'\n\nexport function CreatePostForm() {\n  return (\n    \u003Cform action={createPost}>\n      \u003Clabel>\n        Title:\n        \u003Cinput type=\"text\" name=\"title\" required \u002F>\n      \u003C\u002Flabel>\n\n      \u003Clabel>\n        Content:\n        \u003Ctextarea name=\"content\" required \u002F>\n      \u003C\u002Flabel>\n\n      \u003Cbutton type=\"submit\">Create Post\u003C\u002Fbutton>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**With Loading State** (useFormStatus):\n```typescript\n'use client'\n\nimport { useFormStatus } from 'react-dom'\nimport { createPost } from '@\u002Fapp\u002Factions'\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus()\n\n  return (\n    \u003Cbutton type=\"submit\" disabled={pending}>\n      {pending ? 'Creating...' : 'Create Post'}\n    \u003C\u002Fbutton>\n  )\n}\n\nexport function CreatePostForm() {\n  return (\n    \u003Cform action={createPost}>\n      \u003Cinput type=\"text\" name=\"title\" required \u002F>\n      \u003Ctextarea name=\"content\" required \u002F>\n      \u003CSubmitButton \u002F>\n    \u003C\u002Fform>\n  )\n}\n```\n\n**With Validation**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nimport { z } from 'zod'\nimport { redirect } from 'next\u002Fnavigation'\n\nconst PostSchema = z.object({\n  title: z.string().min(3, 'Title must be at least 3 characters'),\n  content: z.string().min(10, 'Content must be at least 10 characters'),\n})\n\nexport async function createPost(formData: FormData) {\n  const rawData = {\n    title: formData.get('title'),\n    content: formData.get('content'),\n  }\n\n  \u002F\u002F Validate\n  const parsed = PostSchema.safeParse(rawData)\n\n  if (!parsed.success) {\n    return {\n      errors: parsed.error.flatten().fieldErrors,\n    }\n  }\n\n  \u002F\u002F Mutate\n  await db.posts.create(parsed.data)\n\n  \u002F\u002F Revalidate and redirect\n  revalidateTag('posts', 'max')\n  redirect('\u002Fposts')\n}\n```\n\n**See Template**: `templates\u002Fserver-actions-form.tsx`\n**See Reference**: `references\u002Fserver-actions-guide.md`\n\n---\n\n### 3. Error Handling\n\n**Pattern**: Return error objects from Server Actions, handle in Client Components.\n\n**Server Action**:\n```typescript\n\u002F\u002F app\u002Factions.ts\n'use server'\n\nexport async function deletePost(id: string) {\n  try {\n    await db.posts.delete({ where: { id } })\n    revalidateTag('posts', 'max')\n    return { success: true }\n  } catch (error) {\n    return {\n      success: false,\n      error: 'Failed to delete post. Please try again.'\n    }\n  }\n}\n```\n\n**Client Component**:\n```typescript\n'use client'\n\nimport { useState } from 'react'\nimport { deletePost } from '@\u002Fapp\u002Factions'\n\nexport function DeleteButton({ postId }: { postId: string }) {\n  const [error, setError] = useState\u003Cstring | null>(null)\n\n  async function handleDelete() {\n    const result = await deletePost(postId)\n\n    if (!result.success) {\n      setError(result.error)\n    }\n  }\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={handleDelete}>Delete Post\u003C\u002Fbutton>\n      {error && \u003Cp className=\"error\">{error}\u003C\u002Fp>}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n---\n\n### 4. Optimistic Updates\n\n**Pattern**: Show UI update immediately, then sync with server.\n\n```typescript\n'use client'\n\nimport { useOptimistic } from 'react'\nimport { likePost } from '@\u002Fapp\u002Factions'\n\nexport function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {\n  const [optimisticLikes, addOptimisticLike] = useOptimistic(\n    initialLikes,\n    (state, amount: number) => state + amount\n  )\n\n  async function handleLike() {\n    \u002F\u002F Update UI immediately\n    addOptimisticLike(1)\n\n    \u002F\u002F Sync with server\n    await likePost(postId)\n  }\n\n  return (\n    \u003Cbutton onClick={handleLike}>\n      ❤️ {optimisticLikes} likes\n    \u003C\u002Fbutton>\n  )\n}\n```\n\n**See Reference**: `references\u002Fserver-actions-guide.md`\n\n---\n\n## Route Handlers\n\nRoute Handlers are server-side API endpoints in the App Router. They replace API Routes from the Pages Router.\n\n### 1. Basic Route Handler\n\n**File**: `app\u002Fapi\u002Fhello\u002Froute.ts`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET() {\n  return NextResponse.json({ message: 'Hello, World!' })\n}\n\nexport async function POST(request: Request) {\n  const body = await request.json()\n\n  return NextResponse.json({\n    message: 'Post created',\n    data: body\n  })\n}\n```\n\n**Supported Methods**: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`\n\n**See Template**: `templates\u002Froute-handler-api.ts`\n\n---\n\n### 2. Dynamic Routes\n\n**File**: `app\u002Fapi\u002Fposts\u002F[id]\u002Froute.ts`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET(\n  request: Request,\n  { params }: { params: Promise\u003C{ id: string }> }\n) {\n  const { id } = await params \u002F\u002F ✅ Await params in Next.js 16\n\n  const post = await db.posts.findUnique({ where: { id } })\n\n  if (!post) {\n    return NextResponse.json(\n      { error: 'Post not found' },\n      { status: 404 }\n    )\n  }\n\n  return NextResponse.json(post)\n}\n\nexport async function DELETE(\n  request: Request,\n  { params }: { params: Promise\u003C{ id: string }> }\n) {\n  const { id } = await params\n\n  await db.posts.delete({ where: { id } })\n\n  return NextResponse.json({ message: 'Post deleted' })\n}\n```\n\n---\n\n### 3. Search Params\n\n**URL**: `\u002Fapi\u002Fposts?tag=javascript&limit=10`\n\n```typescript\nimport { NextResponse } from 'next\u002Fserver'\n\nexport async function GET(request: Request) {\n  const { searchParams } = new URL(request.url)\n  const tag = searchParams.get('tag')\n  const limit = parseInt(searchParams.get('limit') || '10')\n\n  const posts = await db.posts.findMany({\n    where: { tags: { has: tag } },\n    take: limit,\n  })\n\n  return NextResponse.json(posts)\n}\n```\n\n---\n\n### 4. Webhooks\n\n**Pattern**: Handle incoming webhooks from third-party services.\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Fstripe\u002Froute.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport { headers } from 'next\u002Fheaders'\n\nexport async function POST(request: Request) {\n  const body = await request.text()\n  const headersList = await headers() \u002F\u002F ✅ Await headers in Next.js 16\n  const signature = headersList.get('stripe-signature')\n\n  \u002F\u002F Verify webhook signature\n  const event = stripe.webhooks.constructEvent(\n    body,\n    signature!,\n    process.env.STRIPE_WEBHOOK_SECRET!\n  )\n\n  \u002F\u002F Handle event\n  switch (event.type) {\n    case 'payment_intent.succeeded':\n      await handlePaymentSuccess(event.data.object)\n      break\n    case 'payment_intent.failed':\n      await handlePaymentFailure(event.data.object)\n      break\n  }\n\n  return NextResponse.json({ received: true })\n}\n```\n\n**See Template**: `templates\u002Froute-handler-api.ts`\n**See Reference**: `references\u002Froute-handlers-reference.md`\n\n---\n\n## Proxy vs Middleware\n\n**Next.js 16 introduces `proxy.ts`** to replace `middleware.ts`.\n\n### Why the Change?\n\n- **`middleware.ts`**: Runs on Edge runtime (limited Node.js APIs)\n- **`proxy.ts`**: Runs on Node.js runtime (full Node.js APIs)\n\nThe new `proxy.ts` makes the network boundary explicit and provides more flexibility.\n\n### Migration\n\n**Before (middleware.ts)**:\n```typescript\n\u002F\u002F middleware.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function middleware(request: NextRequest) {\n  \u002F\u002F Check auth\n  const token = request.cookies.get('token')\n\n  if (!token) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url))\n  }\n\n  return NextResponse.next()\n}\n\nexport const config = {\n  matcher: '\u002Fdashboard\u002F:path*',\n}\n```\n\n**After (proxy.ts)**:\n```typescript\n\u002F\u002F proxy.ts\nimport { NextResponse } from 'next\u002Fserver'\nimport type { NextRequest } from 'next\u002Fserver'\n\nexport function proxy(request: NextRequest) {\n  \u002F\u002F Check auth\n  const token = request.cookies.get('token')\n\n  if (!token) {\n    return NextResponse.redirect(new URL('\u002Flogin', request.url))\n  }\n\n  return NextResponse.next()\n}\n\nexport const config = {\n  matcher: '\u002Fdashboard\u002F:path*',\n}\n```\n\n**See Template**: `templates\u002Fproxy-migration.ts`\n**See Reference**: `references\u002Fproxy-vs-middleware.md`\n\n---\n\n## Parallel Routes & Route Groups\n\n### 1. Parallel Routes\n\n**Use Case**: Render multiple pages in the same layout (e.g., modal + main content, dashboard panels).\n\n**Structure**:\n```\napp\u002F\n├── @modal\u002F\n│   ├── login\u002F\n│   │   └── page.tsx\n│   └── default.tsx  ← REQUIRED in Next.js 16\n├── @feed\u002F\n│   ├── trending\u002F\n│   │   └── page.tsx\n│   └── default.tsx  ← REQUIRED in Next.js 16\n└── layout.tsx\n```\n\n**Layout**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nexport default function Layout({\n  children,\n  modal,\n  feed,\n}: {\n  children: React.ReactNode\n  modal: React.ReactNode\n  feed: React.ReactNode\n}) {\n  return (\n    \u003Chtml>\n      \u003Cbody>\n        {modal}\n        \u003Cmain>\n          {children}\n          \u003Caside>{feed}\u003C\u002Faside>\n        \u003C\u002Fmain>\n      \u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Default Files (REQUIRED)**:\n```typescript\n\u002F\u002F app\u002F@modal\u002Fdefault.tsx\nexport default function ModalDefault() {\n  return null\n}\n\n\u002F\u002F app\u002F@feed\u002Fdefault.tsx\nexport default function FeedDefault() {\n  return \u003Cdiv>Default Feed\u003C\u002Fdiv>\n}\n```\n\n**See Template**: `templates\u002Fparallel-routes-with-default.tsx`\n\n---\n\n### 2. Route Groups\n\n**Use Case**: Organize routes without affecting URL structure.\n\n**Structure**:\n```\napp\u002F\n├── (marketing)\u002F\n│   ├── about\u002F\n│   │   └── page.tsx       → \u002Fabout\n│   └── contact\u002F\n│       └── page.tsx       → \u002Fcontact\n├── (shop)\u002F\n│   ├── products\u002F\n│   │   └── page.tsx       → \u002Fproducts\n│   └── cart\u002F\n│       └── page.tsx       → \u002Fcart\n└── layout.tsx\n```\n\n**Different Layouts per Group**:\n```\napp\u002F\n├── (marketing)\u002F\n│   ├── layout.tsx          ← Marketing layout\n│   └── about\u002Fpage.tsx\n├── (shop)\u002F\n│   ├── layout.tsx          ← Shop layout\n│   └── products\u002Fpage.tsx\n└── layout.tsx              ← Root layout\n```\n\n**See Reference**: `references\u002Fapp-router-fundamentals.md`\n\n---\n\n## React 19.2 Features\n\nNext.js 16 integrates React 19.2, which includes new features from React Canary.\n\n### 1. View Transitions\n\n**Use Case**: Smooth animations between page transitions.\n\n```typescript\n'use client'\n\nimport { useRouter } from 'next\u002Fnavigation'\nimport { startTransition } from 'react'\n\nexport function NavigationLink({ href, children }: { href: string; children: React.ReactNode }) {\n  const router = useRouter()\n\n  function handleClick(e: React.MouseEvent) {\n    e.preventDefault()\n\n    \u002F\u002F Wrap navigation in startTransition for View Transitions\n    startTransition(() => {\n      router.push(href)\n    })\n  }\n\n  return \u003Ca href={href} onClick={handleClick}>{children}\u003C\u002Fa>\n}\n```\n\n**With CSS View Transitions API**:\n```css\n\u002F* app\u002Fglobals.css *\u002F\n@view-transition {\n  navigation: auto;\n}\n\n\u002F* Animate elements with view-transition-name *\u002F\n.page-title {\n  view-transition-name: page-title;\n}\n```\n\n**See Template**: `templates\u002Fview-transitions-react-19.tsx`\n\n---\n\n### 2. `useEffectEvent()` (Experimental)\n\n**Use Case**: Extract non-reactive logic from `useEffect`.\n\n```typescript\n'use client'\n\nimport { useEffect, experimental_useEffectEvent as useEffectEvent } from 'react'\n\nexport function ChatRoom({ roomId }: { roomId: string }) {\n  const onConnected = useEffectEvent(() => {\n    console.log('Connected to room:', roomId)\n  })\n\n  useEffect(() => {\n    const connection = connectToRoom(roomId)\n    onConnected() \u002F\u002F Non-reactive callback\n\n    return () => connection.disconnect()\n  }, [roomId]) \u002F\u002F Only re-run when roomId changes\n\n  return \u003Cdiv>Chat Room {roomId}\u003C\u002Fdiv>\n}\n```\n\n**Why Use It**: Prevents unnecessary `useEffect` re-runs when callback dependencies change.\n\n---\n\n### 3. React Compiler (Stable)\n\n**Use Case**: Automatic memoization without `useMemo`, `useCallback`.\n\n**Enable in next.config.ts**:\n```typescript\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  experimental: {\n    reactCompiler: true,\n  },\n}\n\nexport default config\n```\n\n**Install Plugin**:\n```bash\nnpm install babel-plugin-react-compiler\n```\n\n**Example** (no manual memoization needed):\n```typescript\n'use client'\n\nexport function ExpensiveList({ items }: { items: string[] }) {\n  \u002F\u002F React Compiler automatically memoizes this\n  const filteredItems = items.filter(item => item.length > 3)\n\n  return (\n    \u003Cul>\n      {filteredItems.map(item => (\n        \u003Cli key={item}>{item}\u003C\u002Fli>\n      ))}\n    \u003C\u002Ful>\n  )\n}\n```\n\n**See Reference**: `references\u002Freact-19-integration.md`\n\n---\n\n## Metadata API\n\nThe Metadata API provides type-safe SEO and social sharing metadata.\n\n### 1. Static Metadata\n\n**Pattern**: Export `metadata` object from page or layout.\n\n```typescript\n\u002F\u002F app\u002Fpage.tsx\nimport type { Metadata } from 'next'\n\nexport const metadata: Metadata = {\n  title: 'My App',\n  description: 'Welcome to my app',\n  openGraph: {\n    title: 'My App',\n    description: 'Welcome to my app',\n    images: ['\u002Fog-image.jpg'],\n  },\n  twitter: {\n    card: 'summary_large_image',\n    title: 'My App',\n    description: 'Welcome to my app',\n    images: ['\u002Ftwitter-image.jpg'],\n  },\n}\n\nexport default function Page() {\n  return \u003Ch1>Home\u003C\u002Fh1>\n}\n```\n\n---\n\n### 2. Dynamic Metadata\n\n**Pattern**: Export `generateMetadata` async function.\n\n```typescript\n\u002F\u002F app\u002Fposts\u002F[id]\u002Fpage.tsx\nimport type { Metadata } from 'next'\n\nexport async function generateMetadata({ params }: { params: Promise\u003C{ id: string }> }): Promise\u003CMetadata> {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return {\n    title: post.title,\n    description: post.excerpt,\n    openGraph: {\n      title: post.title,\n      description: post.excerpt,\n      images: [post.coverImage],\n    },\n  }\n}\n\nexport default async function PostPage({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return \u003Carticle>{post.content}\u003C\u002Farticle>\n}\n```\n\n---\n\n### 3. Sitemap\n\n**File**: `app\u002Fsitemap.ts`\n\n```typescript\nimport type { MetadataRoute } from 'next'\n\nexport default async function sitemap(): Promise\u003CMetadataRoute.Sitemap> {\n  const posts = await fetch('\u002Fapi\u002Fposts').then(r => r.json())\n\n  const postUrls = posts.map((post: { id: string; updatedAt: string }) => ({\n    url: `https:\u002F\u002Fexample.com\u002Fposts\u002F${post.id}`,\n    lastModified: post.updatedAt,\n    changeFrequency: 'weekly' as const,\n    priority: 0.8,\n  }))\n\n  return [\n    {\n      url: 'https:\u002F\u002Fexample.com',\n      lastModified: new Date(),\n      changeFrequency: 'daily',\n      priority: 1,\n    },\n    ...postUrls,\n  ]\n}\n```\n\n**See Template**: `templates\u002Fmetadata-config.ts`\n**See Reference**: `references\u002Fmetadata-api-guide.md`\n\n---\n\n## Image & Font Optimization\n\n### 1. next\u002Fimage\n\n**Basic Usage**:\n```typescript\nimport Image from 'next\u002Fimage'\n\nexport function MyImage() {\n  return (\n    \u003CImage\n      src=\"\u002Fhero.jpg\"\n      alt=\"Hero image\"\n      width={1200}\n      height={600}\n      priority \u002F\u002F Load above the fold\n    \u002F>\n  )\n}\n```\n\n**Responsive Images**:\n```typescript\n\u003CImage\n  src=\"\u002Fhero.jpg\"\n  alt=\"Hero\"\n  fill\n  style={{ objectFit: 'cover' }}\n  sizes=\"(max-width: 768px) 100vw, 50vw\"\n\u002F>\n```\n\n**Remote Images** (configure in next.config.ts):\n```typescript\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  images: {\n    remotePatterns: [\n      {\n        protocol: 'https',\n        hostname: 'cdn.example.com',\n        pathname: '\u002Fimages\u002F**',\n      },\n    ],\n  },\n}\n\nexport default config\n```\n\n**See Template**: `templates\u002Fimage-optimization.tsx`\n\n---\n\n### 2. next\u002Ffont\n\n**Google Fonts**:\n```typescript\n\u002F\u002F app\u002Flayout.tsx\nimport { Inter, Roboto_Mono } from 'next\u002Ffont\u002Fgoogle'\n\nconst inter = Inter({\n  subsets: ['latin'],\n  display: 'swap',\n  variable: '--font-inter',\n})\n\nconst robotoMono = Roboto_Mono({\n  subsets: ['latin'],\n  display: 'swap',\n  variable: '--font-roboto-mono',\n})\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n  return (\n    \u003Chtml lang=\"en\" className={`${inter.variable} ${robotoMono.variable}`}>\n      \u003Cbody>{children}\u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n**Local Fonts**:\n```typescript\nimport localFont from 'next\u002Ffont\u002Flocal'\n\nconst myFont = localFont({\n  src: '.\u002Ffonts\u002Fmy-font.woff2',\n  display: 'swap',\n  variable: '--font-my-font',\n})\n```\n\n**See Template**: `templates\u002Ffont-optimization.tsx`\n\n---\n\n## Performance Patterns\n\n### 1. Lazy Loading\n\n**Component Lazy Loading**:\n```typescript\nimport dynamic from 'next\u002Fdynamic'\n\nconst HeavyComponent = dynamic(() => import('.\u002Fheavy-component'), {\n  loading: () => \u003Cdiv>Loading...\u003C\u002Fdiv>,\n  ssr: false, \u002F\u002F Disable SSR for client-only components\n})\n\nexport default function Page() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>My Page\u003C\u002Fh1>\n      \u003CHeavyComponent \u002F>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n**Conditional Loading**:\n```typescript\n'use client'\n\nimport { useState } from 'react'\nimport dynamic from 'next\u002Fdynamic'\n\nconst Chart = dynamic(() => import('.\u002Fchart'), { ssr: false })\n\nexport function Dashboard() {\n  const [showChart, setShowChart] = useState(false)\n\n  return (\n    \u003Cdiv>\n      \u003Cbutton onClick={() => setShowChart(true)}>Show Chart\u003C\u002Fbutton>\n      {showChart && \u003CChart \u002F>}\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n---\n\n### 2. Code Splitting\n\n**Route-level Splitting** (automatic):\n```\napp\u002F\n├── page.tsx       → Bundles: \u002F, shared\n├── about\u002F\n│   └── page.tsx   → Bundles: \u002Fabout, shared\n└── products\u002F\n    └── page.tsx   → Bundles: \u002Fproducts, shared\n```\n\n**Component-level Splitting** (with dynamic import):\n```typescript\nconst Analytics = dynamic(() => import('.\u002Fanalytics'))\nconst Comments = dynamic(() => import('.\u002Fcomments'))\n\nexport default function BlogPost() {\n  return (\n    \u003Carticle>\n      \u003Ch1>Post Title\u003C\u002Fh1>\n      \u003Cp>Content...\u003C\u002Fp>\n      \u003CAnalytics \u002F> {\u002F* Separate bundle *\u002F}\n      \u003CComments \u002F>  {\u002F* Separate bundle *\u002F}\n    \u003C\u002Farticle>\n  )\n}\n```\n\n---\n\n### 3. Turbopack (Stable in Next.js 16)\n\n**Default**: Turbopack is now the default bundler in Next.js 16.\n\n**Metrics**:\n- **2–5× faster production builds**\n- **Up to 10× faster Fast Refresh**\n\n**Opt-out** (if needed):\n```bash\nnpm run build -- --webpack\n```\n\n**Enable File System Caching** (beta):\n```typescript\n\u002F\u002F next.config.ts\nimport type { NextConfig } from 'next'\n\nconst config: NextConfig = {\n  experimental: {\n    turbopack: {\n      fileSystemCaching: true, \u002F\u002F Beta: Persist cache between runs\n    },\n  },\n}\n\nexport default config\n```\n\n**See Reference**: `references\u002Fperformance-optimization.md`\n\n---\n\n## TypeScript Configuration\n\n### 1. Strict Mode\n\n**Enable strict mode** in `tsconfig.json`:\n```json\n{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"noImplicitOverride\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true\n  }\n}\n```\n\n---\n\n### 2. Path Aliases\n\n**Configure in tsconfig.json**:\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@\u002F*\": [\".\u002Fapp\u002F*\"],\n      \"@\u002Fcomponents\u002F*\": [\".\u002Fapp\u002Fcomponents\u002F*\"],\n      \"@\u002Flib\u002F*\": [\".\u002Flib\u002F*\"],\n      \"@\u002Fstyles\u002F*\": [\".\u002Fstyles\u002F*\"]\n    }\n  }\n}\n```\n\n**Usage**:\n```typescript\n\u002F\u002F Instead of: import { Button } from '..\u002F..\u002F..\u002Fcomponents\u002Fbutton'\nimport { Button } from '@\u002Fcomponents\u002Fbutton'\n```\n\n---\n\n### 3. Type-Safe Routing\n\n**Generate types from routes**:\n```bash\nnpm run build\n```\n\n**Usage**:\n```typescript\nimport { useRouter } from 'next\u002Fnavigation'\n\nconst router = useRouter()\n\n\u002F\u002F Type-safe routing\nrouter.push('\u002Fposts\u002F123') \u002F\u002F ✅ Valid route\nrouter.push('\u002Finvalid')   \u002F\u002F ❌ Type error if route doesn't exist\n```\n\n**See Reference**: `references\u002Ftypescript-configuration.md`\n\n---\n\n## Common Errors & Solutions\n\n### 1. Error: `params` is a Promise\n\n**Error**:\n```\nType 'Promise\u003C{ id: string }>' is not assignable to type '{ id: string }'\n```\n\n**Cause**: Next.js 16 changed `params` to async.\n\n**Solution**: Await `params`:\n```typescript\n\u002F\u002F ❌ Before\nexport default function Page({ params }: { params: { id: string } }) {\n  const id = params.id\n}\n\n\u002F\u002F ✅ After\nexport default async function Page({ params }: { params: Promise\u003C{ id: string }> }) {\n  const { id } = await params\n}\n```\n\n---\n\n### 2. Error: `searchParams` is a Promise\n\n**Error**:\n```\nProperty 'query' does not exist on type 'Promise\u003C{ query: string }>'\n```\n\n**Cause**: `searchParams` is now async in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nexport default function Page({ searchParams }: { searchParams: { query: string } }) {\n  const query = searchParams.query\n}\n\n\u002F\u002F ✅ After\nexport default async function Page({ searchParams }: { searchParams: Promise\u003C{ query: string }> }) {\n  const { query } = await searchParams\n}\n```\n\n---\n\n### 3. Error: `cookies()` requires await\n\n**Error**:\n```\n'cookies' implicitly has return type 'any'\n```\n\n**Cause**: `cookies()` is now async in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nimport { cookies } from 'next\u002Fheaders'\n\nexport function MyComponent() {\n  const cookieStore = cookies()\n}\n\n\u002F\u002F ✅ After\nimport { cookies } from 'next\u002Fheaders'\n\nexport async function MyComponent() {\n  const cookieStore = await cookies()\n}\n```\n\n---\n\n### 4. Error: Parallel route missing `default.js`\n\n**Error**:\n```\nError: Parallel route @modal\u002Flogin was matched but no default.js was found\n```\n\n**Cause**: Next.js 16 requires `default.js` for all parallel routes.\n\n**Solution**: Add `default.tsx` files:\n```typescript\n\u002F\u002F app\u002F@modal\u002Fdefault.tsx\nexport default function ModalDefault() {\n  return null\n}\n```\n\n---\n\n### 5. Error: `revalidateTag()` requires 2 arguments\n\n**Error**:\n```\nExpected 2 arguments, but got 1\n```\n\n**Cause**: `revalidateTag()` now requires a `cacheLife` argument in Next.js 16.\n\n**Solution**:\n```typescript\n\u002F\u002F ❌ Before\nrevalidateTag('posts')\n\n\u002F\u002F ✅ After\nrevalidateTag('posts', 'max')\n```\n\n---\n\n### 6. Error: Cannot use React hooks in Server Component\n\n**Error**:\n```\nYou're importing a component that needs useState. It only works in a Client Component\n```\n\n**Cause**: Using React hooks in Server Component.\n\n**Solution**: Add `'use client'` directive:\n```typescript\n\u002F\u002F ✅ Add 'use client' at the top\n'use client'\n\nimport { useState } from 'react'\n\nexport function Counter() {\n  const [count, setCount] = useState(0)\n  return \u003Cbutton onClick={() => setCount(count + 1)}>{count}\u003C\u002Fbutton>\n}\n```\n\n---\n\n### 7. Error: `middleware.ts` is deprecated\n\n**Warning**:\n```\nWarning: middleware.ts is deprecated. Use proxy.ts instead.\n```\n\n**Solution**: Migrate to `proxy.ts`:\n```typescript\n\u002F\u002F Rename: middleware.ts → proxy.ts\n\u002F\u002F Rename function: middleware → proxy\n\nexport function proxy(request: NextRequest) {\n  \u002F\u002F Same logic\n}\n```\n\n---\n\n### 8. Error: Turbopack build failure\n\n**Error**:\n```\nError: Failed to compile with Turbopack\n```\n\n**Cause**: Turbopack is now default in Next.js 16.\n\n**Solution**: Opt out of Turbopack if incompatible:\n```bash\nnpm run build -- --webpack\n```\n\n---\n\n### 9. Error: Invalid `next\u002Fimage` src\n\n**Error**:\n```\nInvalid src prop (https:\u002F\u002Fexample.com\u002Fimage.jpg) on `next\u002Fimage`. Hostname \"example.com\" is not configured under images in your `next.config.js`\n```\n\n**Solution**: Add remote patterns in `next.config.ts`:\n```typescript\nconst config: NextConfig = {\n  images: {\n    remotePatterns: [\n      {\n        protocol: 'https',\n        hostname: 'example.com',\n      },\n    ],\n  },\n}\n```\n\n---\n\n### 10. Error: Cannot import Server Component into Client Component\n\n**Error**:\n```\nYou're importing a Server Component into a Client Component\n```\n\n**Solution**: Pass Server Component as children:\n```typescript\n\u002F\u002F ❌ Wrong\n'use client'\nimport { ServerComponent } from '.\u002Fserver-component' \u002F\u002F Error\n\nexport function ClientComponent() {\n  return \u003CServerComponent \u002F>\n}\n\n\u002F\u002F ✅ Correct\n'use client'\n\nexport function ClientComponent({ children }: { children: React.ReactNode }) {\n  return \u003Cdiv>{children}\u003C\u002Fdiv>\n}\n\n\u002F\u002F Usage\n\u003CClientComponent>\n  \u003CServerComponent \u002F> {\u002F* Pass as children *\u002F}\n\u003C\u002FClientComponent>\n```\n\n---\n\n### 11. Error: `generateStaticParams` not working\n\n**Cause**: `generateStaticParams` only works with static generation (`export const dynamic = 'force-static'`).\n\n**Solution**:\n```typescript\nexport const dynamic = 'force-static'\n\nexport async function generateStaticParams() {\n  const posts = await fetch('\u002Fapi\u002Fposts').then(r => r.json())\n  return posts.map((post: { id: string }) => ({ id: post.id }))\n}\n```\n\n---\n\n### 12. Error: `fetch()` not caching\n\n**Cause**: Next.js 16 uses opt-in caching with `\"use cache\"` directive.\n\n**Solution**: Add `\"use cache\"` to component or function:\n```typescript\n'use cache'\n\nexport async function getPosts() {\n  const response = await fetch('\u002Fapi\u002Fposts')\n  return response.json()\n}\n```\n\n---\n\n### 13. Error: Route collision with Route Groups\n\n**Error**:\n```\nError: Conflicting routes: \u002Fabout and \u002F(marketing)\u002Fabout\n```\n\n**Cause**: Route groups create same URL path.\n\n**Solution**: Ensure route groups don't conflict:\n```\napp\u002F\n├── (marketing)\u002Fabout\u002Fpage.tsx  → \u002Fabout\n└── (shop)\u002Fabout\u002Fpage.tsx       → ERROR: Duplicate \u002Fabout\n\n# Fix: Use different routes\napp\u002F\n├── (marketing)\u002Fabout\u002Fpage.tsx     → \u002Fabout\n└── (shop)\u002Fstore-info\u002Fpage.tsx     → \u002Fstore-info\n```\n\n---\n\n### 14. Error: Metadata not updating\n\n**Cause**: Using dynamic metadata without `generateMetadata()`.\n\n**Solution**: Use `generateMetadata()` for dynamic pages:\n```typescript\nexport async function generateMetadata({ params }: { params: Promise\u003C{ id: string }> }): Promise\u003CMetadata> {\n  const { id } = await params\n  const post = await fetch(`\u002Fapi\u002Fposts\u002F${id}`).then(r => r.json())\n\n  return {\n    title: post.title,\n    description: post.excerpt,\n  }\n}\n```\n\n---\n\n### 15. Error: `next\u002Ffont` font not loading\n\n**Cause**: Font variable not applied to HTML element.\n\n**Solution**: Apply font variable to `\u003Chtml>` or `\u003Cbody>`:\n```typescript\nimport { Inter } from 'next\u002Ffont\u002Fgoogle'\n\nconst inter = Inter({ subsets: ['latin'], variable: '--font-inter' })\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n  return (\n    \u003Chtml className={inter.variable}> {\u002F* ✅ Apply variable *\u002F}\n      \u003Cbody>{children}\u003C\u002Fbody>\n    \u003C\u002Fhtml>\n  )\n}\n```\n\n---\n\n### 16. Error: Environment variables not available in browser\n\n**Cause**: Server-only env vars are not exposed to browser.\n\n**Solution**: Prefix with `NEXT_PUBLIC_` for client-side access:\n```bash\n# .env\nSECRET_KEY=abc123                  # Server-only\nNEXT_PUBLIC_API_URL=https:\u002F\u002Fapi    # Available in browser\n```\n\n```typescript\n\u002F\u002F Server Component (both work)\nconst secret = process.env.SECRET_KEY\nconst apiUrl = process.env.NEXT_PUBLIC_API_URL\n\n\u002F\u002F Client Component (only public vars work)\nconst apiUrl = process.env.NEXT_PUBLIC_API_URL\n```\n\n---\n\n### 17. Error: Server Action not found\n\n**Error**:\n```\nError: Could not find Server Action\n```\n\n**Cause**: Missing `'use server'` directive.\n\n**Solution**: Add `'use server'`:\n```typescript\n\u002F\u002F ❌ Before\nexport async function createPost(formData: FormData) {\n  await db.posts.create({ ... })\n}\n\n\u002F\u002F ✅ After\n'use server'\n\nexport async function createPost(formData: FormData) {\n  await db.posts.create({ ... })\n}\n```\n\n---\n\n### 18. Error: TypeScript path alias not working\n\n**Cause**: Incorrect `baseUrl` or `paths` in `tsconfig.json`.\n\n**Solution**: Configure correctly:\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@\u002F*\": [\".\u002F*\"],\n      \"@\u002Fcomponents\u002F*\": [\".\u002Fapp\u002Fcomponents\u002F*\"]\n    }\n  }\n}\n```\n\n**See Reference**: `references\u002Ftop-errors.md`\n\n---\n\n## Templates Reference\n\nThe following templates are available in `templates\u002F`:\n\n**App Router Fundamentals**:\n- `app-router-async-params.tsx` - Async params, searchParams patterns (Next.js 16)\n- `parallel-routes-with-default.tsx` - Parallel routes with required default.js\n- `route-groups-example.tsx` - Route groups organization\n\n**Cache Components (Next.js 16)**:\n- `cache-component-use-cache.tsx` - Cache Components with `\"use cache\"`\n- `partial-prerendering.tsx` - PPR with static + dynamic parts\n- `revalidate-tag-cache-life.ts` - Updated `revalidateTag()` API\n- `server-action-update-tag.ts` - `updateTag()` for read-your-writes\n\n**Server Components**:\n- `server-component-data-fetching.tsx` - Data fetching patterns\n- `server-component-streaming.tsx` - Streaming with Suspense\n- `server-component-composition.tsx` - Server + Client component composition\n\n**Server Actions**:\n- `server-actions-form.tsx` - Form handling with Server Actions\n- `server-actions-validation.ts` - Server Action validation with Zod\n- `server-actions-optimistic.tsx` - Optimistic updates\n\n**Route Handlers**:\n- `route-handler-api.ts` - Basic CRUD API\n- `route-handler-webhook.ts` - Webhook handling\n- `route-handler-streaming.ts` - Streaming responses\n\n**Proxy & Middleware**:\n- `proxy-migration.ts` - Migrate from middleware.ts to proxy.ts\n- `proxy-auth.ts` - Auth with proxy.ts\n\n**React 19.2**:\n- `view-transitions-react-19.tsx` - View Transitions API\n- `use-effect-event.tsx` - `useEffectEvent()` pattern\n- `react-compiler-example.tsx` - React Compiler usage\n\n**Metadata**:\n- `metadata-config.ts` - Static and dynamic metadata\n- `sitemap.ts` - Sitemap generation\n- `robots.ts` - robots.txt generation\n\n**Optimization**:\n- `image-optimization.tsx` - next\u002Fimage patterns\n- `font-optimization.tsx` - next\u002Ffont patterns\n- `lazy-loading.tsx` - Dynamic imports and lazy loading\n- `code-splitting.tsx` - Code splitting strategies\n\n**TypeScript**:\n- `typescript-config.json` - Recommended TypeScript configuration\n- `path-aliases.tsx` - Path alias usage\n\n**Configuration**:\n- `next.config.ts` - Full Next.js configuration\n- `package.json` - Recommended dependencies for Next.js 16\n\n---\n\n## Additional Resources\n\n**Bundled References** (in `references\u002F`):\n- `next-16-migration-guide.md` - Complete migration from Next.js 15 to 16\n- `cache-components-guide.md` - Cache Components deep dive\n- `proxy-vs-middleware.md` - Proxy.ts vs middleware.ts comparison\n- `async-route-params.md` - Async params, searchParams, cookies(), headers()\n- `app-router-fundamentals.md` - App Router concepts and patterns\n- `server-components-patterns.md` - Server Components best practices\n- `server-actions-guide.md` - Server Actions patterns and validation\n- `route-handlers-reference.md` - Route Handlers API reference\n- `metadata-api-guide.md` - Metadata API complete guide\n- `performance-optimization.md` - Performance patterns and Turbopack\n- `react-19-integration.md` - React 19.2 features in Next.js\n- `top-errors.md` - 18+ common errors and solutions\n\n**Scripts**:\n- `scripts\u002Fcheck-versions.sh` - Verify Next.js and dependency versions\n\n**External Documentation**:\n- **Next.js 16 Blog**: https:\u002F\u002Fnextjs.org\u002Fblog\u002Fnext-16\n- **Next.js Docs**: https:\u002F\u002Fnextjs.org\u002Fdocs\n- **React Docs**: https:\u002F\u002Freact.dev\n- **Context7 MCP**: Use `\u002Fwebsites\u002Fnextjs` for latest Next.js reference\n\n---\n\n## Version Compatibility\n\n| Package | Minimum Version | Recommended |\n|---------|----------------|-------------|\n| Next.js | 16.0.0 | 16.0.0+ |\n| React | 19.2.0 | 19.2.0+ |\n| Node.js | 20.9.0 | 20.9.0+ |\n| TypeScript | 5.1.0 | 5.7.0+ |\n| Turbopack | (built-in) | Stable |\n\n**Check Versions**:\n```bash\n.\u002Fscripts\u002Fcheck-versions.sh\n```\n\n---\n\n## Token Efficiency\n\n**Estimated Token Savings**: 65-70%\n\n**Without Skill** (manual setup from docs):\n- Read Next.js 16 migration guide: ~5k tokens\n- Read App Router docs: ~8k tokens\n- Read Server Actions docs: ~4k tokens\n- Read Metadata API docs: ~3k tokens\n- Trial-and-error fixes: ~8k tokens\n- **Total**: ~28k tokens\n\n**With Skill**:\n- Load skill: ~8k tokens\n- Use templates: ~2k tokens\n- **Total**: ~10k tokens\n- **Savings**: ~18k tokens (~64%)\n\n**Errors Prevented**: 18+ common mistakes = 100% error prevention\n\n---\n\n## Maintenance\n\n**Last Verified**: 2025-10-24\n**Next Review**: 2026-01-24 (Quarterly)\n**Maintainer**: Jezweb | jeremy@jezweb.net\n**Repository**: https:\u002F\u002Fgithub.com\u002Fjezweb\u002Fclaude-skills\n\n**Update Triggers**:\n- Next.js major\u002Fminor releases\n- React major releases\n- Breaking changes in APIs\n- New Turbopack features\n\n**Version Check**:\n```bash\ncd skills\u002Fnextjs\n.\u002Fscripts\u002Fcheck-versions.sh\n```\n\n---\n\n**End of SKILL.md**\n",{"name":5,"license":14,"metadata":23,"description":34,"allowed-tools":35},{"author":24,"version":25,"repository":26,"node_version":27,"last_verified":28,"react_version":29,"token_savings":30,"nextjs_version":31,"errors_prevented":32,"production_tested":33},"Jezweb","1.0.0","https:\u002F\u002Fgithub.com\u002Fjezweb\u002Fclaude-skills","20.9+",1761264000000,"19.2.0","65-70%","16.0.0","18+",true,"Use this skill for Next.js App Router patterns, Server Components, Server Actions, Cache Components, and framework-level optimizations. Covers Next.js 16 breaking changes including async params, proxy.ts migration, Cache Components with \"use cache\", and React 19.2 integration. For deploying to Cloudflare Workers, use the cloudflare-nextjs skill instead. This skill is deployment-agnostic and works with Vercel, AWS, self-hosted, or any platform.\n\nKeywords: Next.js 16, Next.js App Router, Next.js Pages Router, Server Components, React Server Components, Server Actions, Cache Components, use cache, Next.js 16 breaking changes, async params nextjs, proxy.ts migration, React 19.2, Next.js metadata, Next.js SEO, generateMetadata, static generation, dynamic rendering, streaming SSR, Suspense, parallel routes, intercepting routes, route groups, Next.js middleware, Next.js API routes, Route Handlers, revalidatePath, revalidateTag, next\u002Fnavigation, useSearchParams, turbopack, next.config\n",[36,37,38,39,40,41],"Read","Write","Edit","Bash","Glob","Grep","main","45d5ac830c3e238eeba6d0b4e6fd7cf6b56bf380","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:05:56",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":33},[49,52,55],{"tool":50,"command":51},"npx","npx skills add davidanthonyn\u002Fclaude-skills --skill nextjs",{"tool":53,"command":54},"bunx","bunx skills add davidanthonyn\u002Fclaude-skills --skill nextjs",{"tool":56,"command":57},"pnpm","pnpm dlx skills add davidanthonyn\u002Fclaude-skills --skill nextjs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fnextjs\u002FSKILL.md",[60,66,70],{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"README.md","REFERENCE","参考文档",14321,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fnextjs\u002FREADME.md",{"path":67,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":68,"sourceHtmlUrl":69},"SKILL.json",64027,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fnextjs\u002FSKILL.json",{"path":71,"resourceType":72,"resourceTypeDesc":73,"sizeBytes":74,"sourceHtmlUrl":75},"SKILL.md.backup","OTHER","其他",58077,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fnextjs\u002FSKILL.md.backup",[77,84,92,99,106,115],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M7AQPHJF528A4MD52YZEZV3R","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":88,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":18},"01M7AQP2XJRPNYEH323GJ81NN5","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":18},"01M7AQNEJHD27NNF5PYQDSW8B9","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":18},"01M7AQJQSD2H04EE2EPNAQ8A3M","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":110,"licenseFileUrl":111,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":18},"01M7AQJ91T970QCFMN9R1EHZXV","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":18},"01M7AQJ5E89MS8C5K3GZTY4B48","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]