[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E1MYTNH2NTY9382VBEVKVD":3,"skill-same:01M6E1MYTNH2NTY9382VBEVKVD":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":6,"ownerDescription":54,"updatedAt":55,"install":56,"resources":69},"01M6E1MYTNH2NTY9382VBEVKVD","nextjs-expert",null,"Expert-level Next.js development. Use when building Next.js apps, working with App Router, Server Components, Client Components, Server Actions, data fetching, middleware, ISR, SSG, SSR, or deploying Next.js. Also use when the user mentions 'App Router', 'Server Actions', 'getServerSideProps', 'middleware', 'ISR', 'use client', 'use server', 'layout.tsx', or 'page.tsx'.","luokai0\u002Fai-agent-skills-by-luo-kai","luokai0","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266954973?v=4","01M6E16VNT42JB8B3X3254QWJ7","luo kai","01M6E16VTFVP6S5XJF1V1MPV90",14,"MIT","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F02-frontend-development (by Luo Kai)\u002F01-react-ecosystem\u002Fnextjs-expert\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"nextjs expert","nextjs","expert","router","client","apps","app","layout","ssg","next","tsx","components","use","page","Next.js","data","actions","server","development","ssr","2026-11-10 10:12:30",false,"---\nauthor: luo-kai\nname: nextjs-expert\ndescription: Expert-level Next.js development. Use when building Next.js apps, working with App Router, Server Components, Client Components, Server Actions, data fetching, middleware, ISR, SSG, SSR, or deploying Next.js. Also use when the user mentions 'App Router', 'Server Actions', 'getServerSideProps', 'middleware', 'ISR', 'use client', 'use server', 'layout.tsx', or 'page.tsx'.\nlicense: MIT\nmetadata:\n  author: luokai0\n  version: \"1.0\"\n  category: coding\n---\n\n# Next.js Expert\n\nYou are an expert Next.js engineer with deep knowledge of the App Router, React Server Components, caching layers, and production deployment patterns.\n\n## Before Starting\n\n1. **Next.js version** — 13, 14, or 15?\n2. **Router** — App Router or Pages Router?\n3. **Deployment** — Vercel, self-hosted Node.js, Docker, edge?\n4. **Data fetching** — database direct, REST API, GraphQL?\n5. **Auth** — NextAuth, Clerk, Auth.js, custom?\n\n---\n\n## Core Expertise Areas\n\n- **App Router**: layout hierarchy, nested layouts, route groups, parallel routes, intercepting routes\n- **Server vs Client Components**: mental model, when to add 'use client', serialization rules\n- **Data fetching**: fetch with caching, generateStaticParams, dynamic rendering triggers\n- **Server Actions**: forms, useFormState, useFormStatus, optimistic updates with useOptimistic\n- **Caching layers**: Request Memoization, Data Cache, Full Route Cache, Router Cache — all four\n- **Middleware**: matcher config, request rewriting, auth patterns, edge runtime limits\n- **Metadata API**: static and dynamic metadata, Open Graph, Twitter cards\n- **Performance**: partial prerendering, streaming, Suspense boundaries, image optimization\n\n---\n\n## Key Patterns & Code\n\n### App Router File Structure\n```\napp\u002F\n  layout.tsx              # Root layout — wraps all pages\n  page.tsx                # Home page \u002F\n  loading.tsx             # Loading UI (automatic Suspense)\n  error.tsx               # Error UI (automatic Error Boundary)\n  not-found.tsx           # 404 page\n  (auth)\u002F                 # Route group — no URL segment\n    login\u002F\n      page.tsx            # \u002Flogin\n    register\u002F\n      page.tsx            # \u002Fregister\n  dashboard\u002F\n    layout.tsx            # Nested layout for \u002Fdashboard\u002F*\n    page.tsx              # \u002Fdashboard\n    @modal\u002F               # Parallel route slot\n      (..)photo\u002F[id]\u002F\n        page.tsx          # Intercepting route\n    [userId]\u002F\n      page.tsx            # \u002Fdashboard\u002F123\n    [...slug]\u002F\n      page.tsx            # \u002Fdashboard\u002Fa\u002Fb\u002Fc\nlib\u002F\n  actions.ts              # Server Actions\n  db.ts                   # Database client (singleton)\n  auth.ts                 # Auth helpers\ncomponents\u002F\n  ui\u002F                     # Shared UI components\n```\n\n### Server vs Client Components\n```tsx\n\u002F\u002F SERVER COMPONENT (default) — runs on server only\n\u002F\u002F ✅ Can: async\u002Fawait, access DB directly, use secrets\n\u002F\u002F ❌ Cannot: useState, useEffect, event handlers, browser APIs\n\n\u002F\u002F app\u002Fusers\u002Fpage.tsx\nimport { db } from \"@\u002Flib\u002Fdb\";\n\nexport default async function UsersPage() {\n  \u002F\u002F Direct DB access — no API needed\n  const users = await db.user.findMany({\n    orderBy: { createdAt: \"desc\" },\n    take: 20,\n  });\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>Users\u003C\u002Fh1>\n      {users.map(user => (\n        \u003CUserCard key={user.id} user={user} \u002F>\n      ))}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F CLIENT COMPONENT — runs on server (for HTML) AND client\n\u002F\u002F ✅ Can: useState, useEffect, event handlers, browser APIs\n\u002F\u002F ❌ Cannot: async\u002Fawait at component level, access secrets\n\n\"use client\";\n\nimport { useState } from \"react\";\n\nexport function SearchBar({ onSearch }: { onSearch: (q: string) => void }) {\n  const [query, setQuery] = useState(\"\");\n\n  return (\n    \u003Cinput\n      value={query}\n      onChange={e => setQuery(e.target.value)}\n      onKeyDown={e => e.key === \"Enter\" && onSearch(query)}\n      placeholder=\"Search...\"\n    \u002F>\n  );\n}\n```\n\n### Data Fetching & Caching\n```tsx\n\u002F\u002F fetch with caching options\nasync function getData(id: string) {\n  \u002F\u002F Static — cached indefinitely (default in static rendering)\n  const static_data = await fetch(`https:\u002F\u002Fapi.example.com\u002Fstatic\u002F${id}`);\n\n  \u002F\u002F Revalidate every 60 seconds (ISR equivalent)\n  const revalidated = await fetch(`https:\u002F\u002Fapi.example.com\u002Fposts`, {\n    next: { revalidate: 60 },\n  });\n\n  \u002F\u002F Dynamic — never cache (always fresh)\n  const dynamic_data = await fetch(`https:\u002F\u002Fapi.example.com\u002Flive\u002F${id}`, {\n    cache: \"no-store\",\n  });\n\n  return { static_data, revalidated, dynamic_data };\n}\n\n\u002F\u002F Parallel data fetching — don't await sequentially\nexport default async function Page({ params }: { params: { id: string } }) {\n  \u002F\u002F ✅ Start both fetches simultaneously\n  const [user, posts] = await Promise.all([\n    getUser(params.id),\n    getUserPosts(params.id),\n  ]);\n\n  return \u003CProfile user={user} posts={posts} \u002F>;\n}\n\n\u002F\u002F generateStaticParams — pre-render dynamic routes at build time\nexport async function generateStaticParams() {\n  const posts = await db.post.findMany({ select: { slug: true } });\n  return posts.map(post => ({ slug: post.slug }));\n}\n```\n\n### Streaming with Suspense\n```tsx\n\u002F\u002F app\u002Fdashboard\u002Fpage.tsx\nimport { Suspense } from \"react\";\n\n\u002F\u002F Page renders immediately with shell\n\u002F\u002F Slow components stream in when ready\nexport default function DashboardPage() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>Dashboard\u003C\u002Fh1>\n\n      {\u002F* Renders immediately — no async *\u002F}\n      \u003CQuickStats \u002F>\n\n      {\u002F* Streams in after slow DB query *\u002F}\n      \u003CSuspense fallback={\u003CRevenueChartSkeleton \u002F>}>\n        \u003CRevenueChart \u002F>    {\u002F* async Server Component *\u002F}\n      \u003C\u002FSuspense>\n\n      {\u002F* Streams in independently *\u002F}\n      \u003CSuspense fallback={\u003CActivityFeedSkeleton \u002F>}>\n        \u003CActivityFeed \u002F>    {\u002F* async Server Component *\u002F}\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Async Server Component\nasync function RevenueChart() {\n  \u002F\u002F This slow query doesn't block the rest of the page\n  const data = await db.order.aggregate({\n    _sum: { total: true },\n    groupBy: [\"month\"],\n  });\n  return \u003CChart data={data} \u002F>;\n}\n```\n\n### Server Actions\n```tsx\n\u002F\u002F lib\u002Factions.ts\n\"use server\";\n\nimport { revalidatePath, revalidateTag } from \"next\u002Fcache\";\nimport { redirect } from \"next\u002Fnavigation\";\nimport { z } from \"zod\";\n\nconst CreatePostSchema = z.object({\n  title: z.string().min(1).max(200),\n  content: z.string().min(10),\n  published: z.boolean().default(false),\n});\n\nexport async function createPost(formData: FormData) {\n  \u002F\u002F Validate\n  const parsed = CreatePostSchema.safeParse({\n    title: formData.get(\"title\"),\n    content: formData.get(\"content\"),\n    published: formData.get(\"published\") === \"on\",\n  });\n\n  if (!parsed.success) {\n    return { error: parsed.error.flatten().fieldErrors };\n  }\n\n  \u002F\u002F Authorize\n  const session = await getSession();\n  if (!session) return { error: { _form: [\"Unauthorized\"] } };\n\n  \u002F\u002F Mutate\n  const post = await db.post.create({\n    data: { ...parsed.data, authorId: session.userId },\n  });\n\n  \u002F\u002F Revalidate cache\n  revalidatePath(\"\u002Fposts\");\n  revalidateTag(\"posts\");\n\n  \u002F\u002F Redirect\n  redirect(`\u002Fposts\u002F${post.id}`);\n}\n\n\u002F\u002F With useFormState for error display\n\"use client\";\nimport { useFormState, useFormStatus } from \"react-dom\";\nimport { createPost } from \"@\u002Flib\u002Factions\";\n\nconst initialState = { error: null };\n\nexport function CreatePostForm() {\n  const [state, formAction] = useFormState(createPost, initialState);\n\n  return (\n    \u003Cform action={formAction}>\n      \u003Cinput name=\"title\" placeholder=\"Title\" \u002F>\n      {state.error?.title && \u003Cp>{state.error.title[0]}\u003C\u002Fp>}\n\n      \u003Ctextarea name=\"content\" placeholder=\"Content\" \u002F>\n      {state.error?.content && \u003Cp>{state.error.content[0]}\u003C\u002Fp>}\n\n      \u003CSubmitButton \u002F>\n    \u003C\u002Fform>\n  );\n}\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    \u003Cbutton type=\"submit\" disabled={pending}>\n      {pending ? \"Creating...\" : \"Create Post\"}\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n### Middleware\n```typescript\n\u002F\u002F middleware.ts (root of project)\nimport { NextResponse } from \"next\u002Fserver\";\nimport type { NextRequest } from \"next\u002Fserver\";\n\nexport function middleware(request: NextRequest) {\n  const { pathname } = request.nextUrl;\n\n  \u002F\u002F Auth check\n  const token = request.cookies.get(\"session\")?.value;\n  const isAuthenticated = !!token; \u002F\u002F validate token here\n\n  const isProtectedRoute = pathname.startsWith(\"\u002Fdashboard\");\n  const isAuthRoute = pathname.startsWith(\"\u002Flogin\");\n\n  if (isProtectedRoute && !isAuthenticated) {\n    return NextResponse.redirect(new URL(\"\u002Flogin\", request.url));\n  }\n\n  if (isAuthRoute && isAuthenticated) {\n    return NextResponse.redirect(new URL(\"\u002Fdashboard\", request.url));\n  }\n\n  \u002F\u002F Add request headers for downstream use\n  const requestHeaders = new Headers(request.headers);\n  requestHeaders.set(\"x-pathname\", pathname);\n\n  return NextResponse.next({\n    request: { headers: requestHeaders },\n  });\n}\n\n\u002F\u002F Only run middleware on these paths\nexport const config = {\n  matcher: [\n    \"\u002F((?!api|_next\u002Fstatic|_next\u002Fimage|favicon.ico).*)\",\n  ],\n};\n```\n\n### Metadata API\n```tsx\n\u002F\u002F Static metadata\nexport const metadata: Metadata = {\n  title: \"My App\",\n  description: \"My app description\",\n  openGraph: {\n    title: \"My App\",\n    description: \"My app description\",\n    images: [\"\u002Fog-image.png\"],\n  },\n};\n\n\u002F\u002F Dynamic metadata\nexport async function generateMetadata(\n  { params }: { params: { id: string } }\n): Promise\u003CMetadata> {\n  const post = await getPost(params.id);\n  if (!post) return { title: \"Not Found\" };\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```\n\n### The Four Caching Layers\n```\n1. Request Memoization (per-render)\n   - Deduplicates identical fetch() calls in the same render tree\n   - Automatic — no configuration needed\n   - Resets after each server request\n\n2. Data Cache (persistent)\n   - Stores fetch() responses on the server\n   - Controlled by: cache: 'no-store' | next: { revalidate: N } | next: { tags: [] }\n   - Persists across deployments until revalidated\n\n3. Full Route Cache (build time)\n   - Caches rendered HTML + RSC payload of static routes\n   - Opt out with: export const dynamic = 'force-dynamic'\n   - Revalidated with: revalidatePath() or revalidateTag()\n\n4. Router Cache (client-side)\n   - Caches RSC payloads in browser memory\n   - Lasts 30s (dynamic) or 5min (static) by default\n   - Cleared on: router.refresh() or server action completion\n```\n\n---\n\n## Best Practices\n\n- Default to Server Components — only add `use client` when needed\n- Fetch data as close to where it's used as possible — in the Server Component itself\n- Use `Promise.all()` for parallel fetches — never sequential awaits\n- Put Suspense boundaries around slow async components for streaming\n- Use Server Actions for mutations — not API routes in App Router\n- Validate and authorize in every Server Action — never trust the client\n- Use `revalidatePath` or `revalidateTag` after mutations\n- Use `next\u002Fimage` for all images — automatic optimization\n- Use `next\u002Ffont` for fonts — eliminates layout shift\n\n---\n\n## Common Pitfalls\n\n| Pitfall | Problem | Fix |\n|---|---|---|\n| `use client` at top of tree | Entire subtree becomes client | Push `use client` as far down as possible |\n| Sequential awaits | Waterfall data fetching | Use Promise.all() for parallel fetches |\n| Secrets in Client Components | Exposed to browser | Only use secrets in Server Components |\n| Missing Suspense boundaries | Page blocks on slow data | Wrap async components in Suspense |\n| Mutating in Server Component | Should only read in RSC | Use Server Actions for mutations |\n| No revalidation after mutation | Stale UI after action | Call revalidatePath\u002FrevalidateTag |\n| fetch in Client Component | Exposes API routes unnecessarily | Fetch in Server Component, pass as props |\n\n---\n\n## Related Skills\n\n- **react-expert**: For React hooks and patterns\n- **typescript-expert**: For Next.js type safety\n- **postgresql-expert**: For database with Next.js\n- **auth-expert**: For authentication patterns\n- **webperf-expert**: For Next.js performance optimization\n- **docker-expert**: For self-hosting Next.js\n","# Next.js Expert\n\nYou are an expert Next.js engineer with deep knowledge of the App Router, React Server Components, caching layers, and production deployment patterns.\n\n## Before Starting\n\n1. **Next.js version** — 13, 14, or 15?\n2. **Router** — App Router or Pages Router?\n3. **Deployment** — Vercel, self-hosted Node.js, Docker, edge?\n4. **Data fetching** — database direct, REST API, GraphQL?\n5. **Auth** — NextAuth, Clerk, Auth.js, custom?\n\n---\n\n## Core Expertise Areas\n\n- **App Router**: layout hierarchy, nested layouts, route groups, parallel routes, intercepting routes\n- **Server vs Client Components**: mental model, when to add 'use client', serialization rules\n- **Data fetching**: fetch with caching, generateStaticParams, dynamic rendering triggers\n- **Server Actions**: forms, useFormState, useFormStatus, optimistic updates with useOptimistic\n- **Caching layers**: Request Memoization, Data Cache, Full Route Cache, Router Cache — all four\n- **Middleware**: matcher config, request rewriting, auth patterns, edge runtime limits\n- **Metadata API**: static and dynamic metadata, Open Graph, Twitter cards\n- **Performance**: partial prerendering, streaming, Suspense boundaries, image optimization\n\n---\n\n## Key Patterns & Code\n\n### App Router File Structure\n```\napp\u002F\n  layout.tsx              # Root layout — wraps all pages\n  page.tsx                # Home page \u002F\n  loading.tsx             # Loading UI (automatic Suspense)\n  error.tsx               # Error UI (automatic Error Boundary)\n  not-found.tsx           # 404 page\n  (auth)\u002F                 # Route group — no URL segment\n    login\u002F\n      page.tsx            # \u002Flogin\n    register\u002F\n      page.tsx            # \u002Fregister\n  dashboard\u002F\n    layout.tsx            # Nested layout for \u002Fdashboard\u002F*\n    page.tsx              # \u002Fdashboard\n    @modal\u002F               # Parallel route slot\n      (..)photo\u002F[id]\u002F\n        page.tsx          # Intercepting route\n    [userId]\u002F\n      page.tsx            # \u002Fdashboard\u002F123\n    [...slug]\u002F\n      page.tsx            # \u002Fdashboard\u002Fa\u002Fb\u002Fc\nlib\u002F\n  actions.ts              # Server Actions\n  db.ts                   # Database client (singleton)\n  auth.ts                 # Auth helpers\ncomponents\u002F\n  ui\u002F                     # Shared UI components\n```\n\n### Server vs Client Components\n```tsx\n\u002F\u002F SERVER COMPONENT (default) — runs on server only\n\u002F\u002F ✅ Can: async\u002Fawait, access DB directly, use secrets\n\u002F\u002F ❌ Cannot: useState, useEffect, event handlers, browser APIs\n\n\u002F\u002F app\u002Fusers\u002Fpage.tsx\nimport { db } from \"@\u002Flib\u002Fdb\";\n\nexport default async function UsersPage() {\n  \u002F\u002F Direct DB access — no API needed\n  const users = await db.user.findMany({\n    orderBy: { createdAt: \"desc\" },\n    take: 20,\n  });\n\n  return (\n    \u003Cdiv>\n      \u003Ch1>Users\u003C\u002Fh1>\n      {users.map(user => (\n        \u003CUserCard key={user.id} user={user} \u002F>\n      ))}\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F CLIENT COMPONENT — runs on server (for HTML) AND client\n\u002F\u002F ✅ Can: useState, useEffect, event handlers, browser APIs\n\u002F\u002F ❌ Cannot: async\u002Fawait at component level, access secrets\n\n\"use client\";\n\nimport { useState } from \"react\";\n\nexport function SearchBar({ onSearch }: { onSearch: (q: string) => void }) {\n  const [query, setQuery] = useState(\"\");\n\n  return (\n    \u003Cinput\n      value={query}\n      onChange={e => setQuery(e.target.value)}\n      onKeyDown={e => e.key === \"Enter\" && onSearch(query)}\n      placeholder=\"Search...\"\n    \u002F>\n  );\n}\n```\n\n### Data Fetching & Caching\n```tsx\n\u002F\u002F fetch with caching options\nasync function getData(id: string) {\n  \u002F\u002F Static — cached indefinitely (default in static rendering)\n  const static_data = await fetch(`https:\u002F\u002Fapi.example.com\u002Fstatic\u002F${id}`);\n\n  \u002F\u002F Revalidate every 60 seconds (ISR equivalent)\n  const revalidated = await fetch(`https:\u002F\u002Fapi.example.com\u002Fposts`, {\n    next: { revalidate: 60 },\n  });\n\n  \u002F\u002F Dynamic — never cache (always fresh)\n  const dynamic_data = await fetch(`https:\u002F\u002Fapi.example.com\u002Flive\u002F${id}`, {\n    cache: \"no-store\",\n  });\n\n  return { static_data, revalidated, dynamic_data };\n}\n\n\u002F\u002F Parallel data fetching — don't await sequentially\nexport default async function Page({ params }: { params: { id: string } }) {\n  \u002F\u002F ✅ Start both fetches simultaneously\n  const [user, posts] = await Promise.all([\n    getUser(params.id),\n    getUserPosts(params.id),\n  ]);\n\n  return \u003CProfile user={user} posts={posts} \u002F>;\n}\n\n\u002F\u002F generateStaticParams — pre-render dynamic routes at build time\nexport async function generateStaticParams() {\n  const posts = await db.post.findMany({ select: { slug: true } });\n  return posts.map(post => ({ slug: post.slug }));\n}\n```\n\n### Streaming with Suspense\n```tsx\n\u002F\u002F app\u002Fdashboard\u002Fpage.tsx\nimport { Suspense } from \"react\";\n\n\u002F\u002F Page renders immediately with shell\n\u002F\u002F Slow components stream in when ready\nexport default function DashboardPage() {\n  return (\n    \u003Cdiv>\n      \u003Ch1>Dashboard\u003C\u002Fh1>\n\n      {\u002F* Renders immediately — no async *\u002F}\n      \u003CQuickStats \u002F>\n\n      {\u002F* Streams in after slow DB query *\u002F}\n      \u003CSuspense fallback={\u003CRevenueChartSkeleton \u002F>}>\n        \u003CRevenueChart \u002F>    {\u002F* async Server Component *\u002F}\n      \u003C\u002FSuspense>\n\n      {\u002F* Streams in independently *\u002F}\n      \u003CSuspense fallback={\u003CActivityFeedSkeleton \u002F>}>\n        \u003CActivityFeed \u002F>    {\u002F* async Server Component *\u002F}\n      \u003C\u002FSuspense>\n    \u003C\u002Fdiv>\n  );\n}\n\n\u002F\u002F Async Server Component\nasync function RevenueChart() {\n  \u002F\u002F This slow query doesn't block the rest of the page\n  const data = await db.order.aggregate({\n    _sum: { total: true },\n    groupBy: [\"month\"],\n  });\n  return \u003CChart data={data} \u002F>;\n}\n```\n\n### Server Actions\n```tsx\n\u002F\u002F lib\u002Factions.ts\n\"use server\";\n\nimport { revalidatePath, revalidateTag } from \"next\u002Fcache\";\nimport { redirect } from \"next\u002Fnavigation\";\nimport { z } from \"zod\";\n\nconst CreatePostSchema = z.object({\n  title: z.string().min(1).max(200),\n  content: z.string().min(10),\n  published: z.boolean().default(false),\n});\n\nexport async function createPost(formData: FormData) {\n  \u002F\u002F Validate\n  const parsed = CreatePostSchema.safeParse({\n    title: formData.get(\"title\"),\n    content: formData.get(\"content\"),\n    published: formData.get(\"published\") === \"on\",\n  });\n\n  if (!parsed.success) {\n    return { error: parsed.error.flatten().fieldErrors };\n  }\n\n  \u002F\u002F Authorize\n  const session = await getSession();\n  if (!session) return { error: { _form: [\"Unauthorized\"] } };\n\n  \u002F\u002F Mutate\n  const post = await db.post.create({\n    data: { ...parsed.data, authorId: session.userId },\n  });\n\n  \u002F\u002F Revalidate cache\n  revalidatePath(\"\u002Fposts\");\n  revalidateTag(\"posts\");\n\n  \u002F\u002F Redirect\n  redirect(`\u002Fposts\u002F${post.id}`);\n}\n\n\u002F\u002F With useFormState for error display\n\"use client\";\nimport { useFormState, useFormStatus } from \"react-dom\";\nimport { createPost } from \"@\u002Flib\u002Factions\";\n\nconst initialState = { error: null };\n\nexport function CreatePostForm() {\n  const [state, formAction] = useFormState(createPost, initialState);\n\n  return (\n    \u003Cform action={formAction}>\n      \u003Cinput name=\"title\" placeholder=\"Title\" \u002F>\n      {state.error?.title && \u003Cp>{state.error.title[0]}\u003C\u002Fp>}\n\n      \u003Ctextarea name=\"content\" placeholder=\"Content\" \u002F>\n      {state.error?.content && \u003Cp>{state.error.content[0]}\u003C\u002Fp>}\n\n      \u003CSubmitButton \u002F>\n    \u003C\u002Fform>\n  );\n}\n\nfunction SubmitButton() {\n  const { pending } = useFormStatus();\n  return (\n    \u003Cbutton type=\"submit\" disabled={pending}>\n      {pending ? \"Creating...\" : \"Create Post\"}\n    \u003C\u002Fbutton>\n  );\n}\n```\n\n### Middleware\n```typescript\n\u002F\u002F middleware.ts (root of project)\nimport { NextResponse } from \"next\u002Fserver\";\nimport type { NextRequest } from \"next\u002Fserver\";\n\nexport function middleware(request: NextRequest) {\n  const { pathname } = request.nextUrl;\n\n  \u002F\u002F Auth check\n  const token = request.cookies.get(\"session\")?.value;\n  const isAuthenticated = !!token; \u002F\u002F validate token here\n\n  const isProtectedRoute = pathname.startsWith(\"\u002Fdashboard\");\n  const isAuthRoute = pathname.startsWith(\"\u002Flogin\");\n\n  if (isProtectedRoute && !isAuthenticated) {\n    return NextResponse.redirect(new URL(\"\u002Flogin\", request.url));\n  }\n\n  if (isAuthRoute && isAuthenticated) {\n    return NextResponse.redirect(new URL(\"\u002Fdashboard\", request.url));\n  }\n\n  \u002F\u002F Add request headers for downstream use\n  const requestHeaders = new Headers(request.headers);\n  requestHeaders.set(\"x-pathname\", pathname);\n\n  return NextResponse.next({\n    request: { headers: requestHeaders },\n  });\n}\n\n\u002F\u002F Only run middleware on these paths\nexport const config = {\n  matcher: [\n    \"\u002F((?!api|_next\u002Fstatic|_next\u002Fimage|favicon.ico).*)\",\n  ],\n};\n```\n\n### Metadata API\n```tsx\n\u002F\u002F Static metadata\nexport const metadata: Metadata = {\n  title: \"My App\",\n  description: \"My app description\",\n  openGraph: {\n    title: \"My App\",\n    description: \"My app description\",\n    images: [\"\u002Fog-image.png\"],\n  },\n};\n\n\u002F\u002F Dynamic metadata\nexport async function generateMetadata(\n  { params }: { params: { id: string } }\n): Promise\u003CMetadata> {\n  const post = await getPost(params.id);\n  if (!post) return { title: \"Not Found\" };\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```\n\n### The Four Caching Layers\n```\n1. Request Memoization (per-render)\n   - Deduplicates identical fetch() calls in the same render tree\n   - Automatic — no configuration needed\n   - Resets after each server request\n\n2. Data Cache (persistent)\n   - Stores fetch() responses on the server\n   - Controlled by: cache: 'no-store' | next: { revalidate: N } | next: { tags: [] }\n   - Persists across deployments until revalidated\n\n3. Full Route Cache (build time)\n   - Caches rendered HTML + RSC payload of static routes\n   - Opt out with: export const dynamic = 'force-dynamic'\n   - Revalidated with: revalidatePath() or revalidateTag()\n\n4. Router Cache (client-side)\n   - Caches RSC payloads in browser memory\n   - Lasts 30s (dynamic) or 5min (static) by default\n   - Cleared on: router.refresh() or server action completion\n```\n\n---\n\n## Best Practices\n\n- Default to Server Components — only add `use client` when needed\n- Fetch data as close to where it's used as possible — in the Server Component itself\n- Use `Promise.all()` for parallel fetches — never sequential awaits\n- Put Suspense boundaries around slow async components for streaming\n- Use Server Actions for mutations — not API routes in App Router\n- Validate and authorize in every Server Action — never trust the client\n- Use `revalidatePath` or `revalidateTag` after mutations\n- Use `next\u002Fimage` for all images — automatic optimization\n- Use `next\u002Ffont` for fonts — eliminates layout shift\n\n---\n\n## Common Pitfalls\n\n| Pitfall | Problem | Fix |\n|---|---|---|\n| `use client` at top of tree | Entire subtree becomes client | Push `use client` as far down as possible |\n| Sequential awaits | Waterfall data fetching | Use Promise.all() for parallel fetches |\n| Secrets in Client Components | Exposed to browser | Only use secrets in Server Components |\n| Missing Suspense boundaries | Page blocks on slow data | Wrap async components in Suspense |\n| Mutating in Server Component | Should only read in RSC | Use Server Actions for mutations |\n| No revalidation after mutation | Stale UI after action | Call revalidatePath\u002FrevalidateTag |\n| fetch in Client Component | Exposes API routes unnecessarily | Fetch in Server Component, pass as props |\n\n---\n\n## Related Skills\n\n- **react-expert**: For React hooks and patterns\n- **typescript-expert**: For Next.js type safety\n- **postgresql-expert**: For database with Next.js\n- **auth-expert**: For authentication patterns\n- **webperf-expert**: For Next.js performance optimization\n- **docker-expert**: For self-hosting Next.js\n",{"name":5,"author":44,"license":15,"metadata":45,"description":7},"luo-kai",{"author":9,"version":46,"category":47},"1.0","coding","main","4d2fb89cdfb75f3f6fd3c6c5ec9ad90ea129eb3c","ai-agent-skills\u002F02-frontend-development (by Luo Kai)\u002F01-react-ecosystem\u002Fnextjs-expert",2,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai","https:\u002F\u002Fgithub.com\u002Fluokai0","a solo builder.","2026-05-06 04:29:04",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill nextjs-expert",{"tool":62,"command":63},"bunx","bunx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill nextjs-expert",{"tool":65,"command":66},"pnpm","pnpm dlx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill nextjs-expert","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F02-frontend-development (by Luo Kai)\u002F01-react-ecosystem\u002Fnextjs-expert\u002FSKILL.md",true,[],[71,98,115,140,165,190],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":39},"01M6F2SKTE208174C7S7JJCZC7","write-contracts","Generates secure Aptos Move V2 smart contracts with Object model, Digital Asset integration, security patterns, and storage type guidance. Includes comprehensive storage decision framework for optimal data structure selection. Triggers on: 'write contract', 'create NFT collection', 'build marketplace', 'implement minting', 'generate Move module', 'create token contract', 'build DAO', 'implement staking'. Ask storage questions when: 'store', 'track', 'registry', 'mapping', 'list', 'collection'.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fwrite-contracts\u002FSKILL.md",[],[78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],"write","contracts","write contracts","storage","secure","create","generate","collection","model","decision","ask","smart-contracts","selection","objects","structure","nft","token","aptos","critical","move",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":39},"01M6F2RFXJ6T9MKW0A7N7GM45B","web-search","通用网络搜索技能，支持多引擎搜索（百度、必应、DuckDuckGo），无需API密钥即可获取实时信息","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fweb-search-ex-skill\u002FSKILL.md",[],[105,106,107,108,109,110,111,112,113,114],"web","search","web search","搜索","baidu","bing","duckduckgo","百度","多引擎","internet",{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":39},"01M6F2K968G1FZEZFPW2E6B222","solo-build","Execute implementation plan tasks with TDD workflow, auto-commit, and phase gates. Use when user says \"build it\", \"start building\", \"execute plan\", \"implement tasks\", \"ship it\", or references a track ID. Do NOT use for planning (use \u002Fplan) or scaffolding (use \u002Fscaffold).","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fsolo-build\u002FSKILL.md",[],[122,123,124,125,126,127,128,129,106,130,131,132,78,133,134,135,136,137,138,139],"build","solo","solo build","MCP","workflow","commit","tasks","code","Bash","plan","read","auto","references","context7","query","scaffolding","ship it","project",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":39},"01M6F2GKN39SGHSPWYB3662YC8","react-email","Use when building HTML email templates with React components, adding a visual email editor to an application using the React Email visual editor, rendering emails to HTML, or sending emails with Resend. Covers welcome emails, password resets, notifications, order confirmations, newsletters, transactional emails, and the embeddable email editor component.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Freact-email-skills\u002FSKILL.md",[],[147,148,149,150,151,30,152,153,154,155,156,157,158,31,159,160,161,162,163,164],"react","email","react email","github","editor","react components","component","welcome","https","notifications","password","node","html","resend","visual","emails","rendering","with",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":171,"publishedAt":39},"01M6F2FBVGVDFSG8SSFJGXA40C","APITester Agent-Driven API Testing","Test API endpoints and document responses. Define tests in plain English, run them, get formatted results. Agent-driven Postman alternative.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fopenclaw-api-tester\u002FSKILL.md",[],[172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189],"testing","api","api testing","driven","APITester Agent Driven API Testing","test","run","postman","results","plain english","tester","endpoints","document","get","define","tests","english","api-tester",{"skillNo":191,"name":192,"nameZh":6,"description":193,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":196,"publishedAt":39},"01M6F273Y3NGAPVJZ608BC0G9G","hubspot-implementation-plan","Generate a phased implementation plan from a HubSpot audit report. Creates prioritized, sequenced cleanup processes with effort estimates, dependencies, and automation feasibility. Use after running \u002Fhubspot-audit.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fhubspot-implementation-plan\u002FSKILL.md",[],[131,197,198,199,200,201,202,84,203,204,205,206,207,31,208,209,164,210],"implementation","hubspot","hubspot implementation plan","automation","feasibility","cleanup","planning","report","audit","audit report","phased implementation","dependencies","processes","hubspot audit"]