Communitygithub.com

Next.js 15 + App Router 專家

在使用 Next.js 15 功能、App Router、伺服器元件、伺服器操作或資料擷取模式時使用。確保正確使用伺服器與用戶端元件以及現代 Next.js 模式。

Next.js 15 + App Router 專家 是什麼?

此技能提供 Next.js 15 App Router 模式的完整參考指南,專為 Quetrex 開發環境設計。它涵蓋檔案式路由、資料擷取、快取策略、伺服器操作、中繼資料 API 和模式驗證等核心主題,並包含超過 150 個範例。技能的核心強調不可違反的規則,例如一律使用 `next/image` 的 `<Image>` 元件而非 `<img>`,以及預設使用伺服器元件,僅在必要時才加入 `'use client'` 指令。對於 AI 代理使用者而言,此技能能確保代理在實作 Next.js 15 應用程式時遵循最佳實務,避免常見錯誤(如非同步客戶端元件或在伺服器元件中使用客戶端 API),從而生成更可靠、效能更佳的程式碼。它支援 Cursor、Claude Code 等現代開發代理,並提供可執行的 Python 驗證腳本,用於自動檢查程式碼符合性。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/barnhardt-enterprises-inc/nextjs-15-specialist

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

預覽

來自技能 README

Next.js 15 + App Router 專家 preview

說明文件

Next.js 15 + App Router 專家 是做什麼的?

完整的 Next.js 15 參考資料,專為 Quetrex 開發而設計。

這項技能提供了所有 Next.js 15 App Router 模式的完整指引,確保代理程式能一次就正確實作現代 Next.js。


關鍵規則(絕不可違反)

這些規則是不可協商的。違反會導致建置失敗。

1. 一律使用 next/image 的 <Image> - 絕對不要使用 <img>

// ✅ 一律這樣做
import Image from 'next/image'

<Image src="/logo.png" alt="Logo" width={200} height={100} />
<Image src={user.avatar} alt={user.name} width={40} height={40} />

// ❌ 絕對不要這樣做 - 建置會失敗
<img src="/logo.png" alt="Logo" />
<img src={user.avatar} alt={user.name} />

原因: Next.js Image 元件提供自動最佳化、延遲載入,並防止版面偏移。ESLint 已設定為在偵測到 <img> 使用時讓建置失敗。

2. 伺服器元件是預設選項 - 只在需要時加入 'use client'

3. 絕不製作非同步的客戶端元件

4. 一律為 fetch() 指定快取策略


何時使用此技能

在處理以下情況時使用此技能:

  • 建立新的路由或頁面
  • 實作資料擷取(伺服器元件 vs 客戶端元件)
  • 伺服器與客戶端元件的決策
  • 伺服器操作與表單處理
  • 串流與 Suspense
  • 中繼資料與 SEO
  • 路由處理器(API 路由)
  • 快取策略
  • 效能最佳化

完整文件

此技能包含涵蓋每個 Next.js 15 模式的完整指南:

📁 App Router 完整指南

超過 45 個範例涵蓋:

  • 檔案式路由 (page.tsx、layout.tsx、route.ts)
  • 動態路由 ([id]、[...slug]、[[...slug]])
  • 路由群組 ((group))
  • 私有資料夾 (_folder)
  • 路由處理器 (API 路由)
  • 佈局與範本
  • 載入 UI (loading.tsx)
  • 錯誤邊界 (error.tsx、global-error.tsx)
  • 找不到頁面 (not-found.tsx)
  • 平行路由 (@folder)
  • 攔截路由 ((.)folder)
  • 路由區段設定 (dynamic、revalidate、runtime)

🔄 資料擷取完整指南

超過 35 個範例涵蓋:

  • 伺服器元件資料擷取 (async/await)
  • 客戶端元件資料擷取 (useEffect、React Query、SWR)
  • 平行資料擷取 (Promise.all)
  • 順序資料擷取(防止瀑布效應)
  • 串流資料 (Suspense 邊界)
  • 伺服器發送事件 (Quetrex 語音的 SSE)
  • 資料變更(伺服器操作)
  • 樂觀更新 (useOptimistic)
  • 表單處理 (useFormStatus、useActionState)
  • 請求去重
  • 預載資料

💾 快取策略指南

超過 35 個範例涵蓋:

  • 請求記憶化(自動去重)
  • 資料快取(fetch 快取行為)
  • 完整路由快取(靜態 vs 動態)
  • 路由器快取(客戶端快取)
  • 快取設定 (force-cache、no-store、revalidate)
  • 快取標籤 (revalidateTag、revalidatePath)
  • 隨需重新驗證
  • 基於時間的重新驗證 (ISR)
  • 快取除錯技術
  • 退出快取

⚡ 伺服器操作完整指南

超過 31 個範例涵蓋:

  • 基本伺服器操作模式
  • 表單操作(漸進增強)
  • 按鈕操作(程式化呼叫)
  • useFormStatus 掛鉤(載入狀態)
  • useActionState 掛鉤(狀態管理)
  • useOptimistic 掛鉤(樂觀 UI)
  • 操作中的錯誤處理
  • 使用 Zod 驗證
  • 回傳 JSON 與重新導向
  • 安全性(身分驗證、CSRF)
  • 速率限制
  • 資料庫交易

🎯 中繼資料 API 指南

超過 26 個範例涵蓋:

  • 靜態中繼資料(匯出的物件)
  • 動態中繼資料 (generateMetadata)
  • 檔案式中繼資料 (icon.png、opengraph-image.png)
  • Open Graph 中繼資料
  • Twitter Cards
  • JSON-LD 結構化資料
  • Viewport 設定
  • PWA 資訊清單
  • Robots.txt
  • Sitemap 產生

✅ 模式驗證器

可執行的 Python 腳本,用於檢查:

  • 伺服器元件未使用僅限客戶端的 API
  • 客戶端元件具有 'use client' 指令
  • 資料擷取使用正確的快取策略
  • 伺服器操作標記為 'use server'
  • 中繼資料 API 使用正確
  • 圖片最佳化(使用 <Image> 而非 <img>)
  • 動態匯入大量元件

執行方式:python validate-patterns.py /path/to/src


快速參考

伺服器與客戶端元件決策樹

是否需要互動性 (onClick、onChange 等)?
├─ 是 → 客戶端元件 ('use client')
└─ 否 → 伺服器元件(預設)

是否需要 React 掛鉤 (useState、useEffect)?
├─ 是 → 客戶端元件
└─ 否 → 伺服器元件

是否需要瀏覽器 API (window、localStorage)?
├─ 是 → 客戶端元件
└─ 否 → 伺服器元件

是否需要擷取資料?
├─ 使用伺服器元件(優先)
└─ 僅在資料必須在客戶端處理時使用客戶端元件

該元件是否純粹是展示性的?
└─ 伺服器元件(效能更佳)

常見模式

1. 伺服器元件資料擷取

// app/projects/page.tsx
export default async function ProjectsPage() {
  const projects = await db.project.findMany()
  return <ProjectList projects={projects} />
}

2. 具有互動性的客戶端元件

// components/ProjectCard.tsx
'use client'

import { useState } from 'react'

export function ProjectCard({ project }: Props) {
  const [loading, setLoading] = useState(false)

  const handleDelete = async () => {
    setLoading(true)
    await deleteProject(project.id)
    setLoading(false)
  }

  return (
    <div>
      <h2>{project.name}</h2>
      <button onClick={handleDelete} disabled={loading}>
        Delete
      </button>
    </div>
  )
}

3. 具有表單的伺服器操作

// app/actions.ts
'use server'

export async function createProject(formData: FormData) {
  const name = formData.get('name') as string
  const project = await db.project.create({ data: { name } })
  revalidatePath('/projects')
  return { success: true, project }
}

// app/projects/new/page.tsx
import { createProject } from '@/app/actions'

export default function NewProjectPage() {
  return (
    <form action={createProject}>
      <input name="name" required />
      <button type="submit">Create</button>
    </form>
  )
}

4. 搭配 Suspense 的串流

// app/dashboard/page.tsx
import { Suspense } from 'react'

export default function DashboardPage() {
  return (
    <div>
      <Suspense fallback={<ProjectsSkeleton />}>
        <ProjectsAsync />
      </Suspense>
      <Suspense fallback={<UsersSkeleton />}>
        <UsersAsync />
      </Suspense>
    </div>
  )
}

async function ProjectsAsync() {
  const projects = await fetchProjects() // 慢速查詢
  return <ProjectList projects={projects} />
}

5. 動態中繼資料

// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>
}): Promise<Metadata> {
  const { slug } = await params
  const post = await fetchPost(slug)

  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [post.coverImage],
    },
  }
}

Quetrex 最佳實務

1. 預設使用伺服器元件

// ✅ 正確做法:伺服器元件(預設)
export default async function ProjectsPage() {
  const projects = await fetchProjects()
  return <ProjectList projects={projects} />
}

// ❌ 錯誤做法:在不需要時使用客戶端元件
'use client'
export default function ProjectsPage() {
  const [projects, setProjects] = useState([])
  useEffect(() => {
    fetchProjects().then(setProjects)
  }, [])
  return <ProjectList projects={projects} />
}

2. 使用正確的快取策略

// 靜態內容(永久快取)
const categories = await fetch('https://api.example.com/categories', {
  cache: 'force-cache',
}).then(r => r.json())

// 動態內容(無快取)
const user = await fetch('https://api.example.com/me', {
  cache: 'no-store',
}).then(r => r.json())

// ISR(每小時重新驗證)
const products = await fetch('https://api.example.com/products', {
  next: { revalidate: 3600 },
}).then(r => r.json())

3. 實作適當的錯誤邊界

// app/dashboard/error.tsx
'use client'

export default function DashboardError({
  error,
  reset,
}: {
  error: Error
  reset: () => void
}) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={reset}>Try again</button>
    </div>
  )
}

4. 使用載入狀態

// app/dashboard/loading.tsx
export default function DashboardLoading() {
  return <DashboardSkeleton />
}

5. 最佳化圖片

// ✅ 正確做法:使用 next/image
import Image from 'next/image'

export function ProjectCard({ project }) {
  return (
    <Image
      src={project.image}
      alt={project.name}
      width={400}
      height={300}
    />
  )
}

// ❌ 錯誤做法:使用 <img> 標籤
export function ProjectCard({ project }) {
  return <img src={project.image} alt={project.name} />
}

應避免的常見錯誤

❌ 錯誤 1:非同步客戶端元件

// ❌ 錯誤做法:這是語法錯誤
'use client'

export default async function BadComponent() {
  const data = await fetch('/api/data')
  return <div>{data}</div>
}

// ✅ 正確做法:使用伺服器元件或 useEffect
export default async function GoodComponent() {
  const data = await fetch('/api/data')
  return <div>{data}</div>
}

❌ 錯誤 2:在伺服器元件中使用客戶端 API

// ❌ 錯誤做法:伺服器元件不能使用瀏覽器 API
export default function BadComponent() {
  const [state, setState] = useState(false) // 錯誤!
  return <div>{state}</div>
}

// ✅ 正確做法:加入 'use client' 指令
'use client'

export default function GoodComponent() {
  const [state, setState] = useState(false)
  return <div>{state}</div>
}

❌ 錯誤 3:缺少快取策略

// ❌ 錯誤做法:不明確的快取行為
const data = await fetch('/api/data')

// ✅ 正確做法:明確的快取策略
const data = await fetch('/api/data', {
  cache: 'no-store', // 或 'force-cache',或 { next: { revalidate: 60 } }
})

❌ 錯誤 4:未使用

// ❌ 錯誤做法:未最佳化的圖片
<img src="/logo.png" alt="Logo" />

// ✅ 正確做法:使用 Next.js Image 最佳化
<Image src="/logo.png" alt="Logo" width={200} height={100} />

疑難排解

錯誤:"You're importing a component that needs useState..."

解決方案: 在元件檔案中加入 'use client'。

錯誤:"async/await is not valid in Client Components"

解決方案: 移除 'use client' 或使用 useEffect 取代非同步元件。

錯誤:"process is not defined"

解決方案: 客戶端元件中的環境變數需要 NEXT_PUBLIC_ 前綴。

錯誤:"Headers already sent"

解決方案: 在傳送回應後不要使用 headers() 或 cookies()。請在任何串流開始之前呼叫它們。


官方文件


驗證

執行程式碼模式驗證器來檢查你的程式碼:

python .claude/skills/nextjs-15-specialist/validate-patterns.py src/

驗證器會檢查:

  • ✅ 非同步客戶端元件(禁止)
  • ✅ 伺服器元件中的客戶端 API
  • ✅ 'use client' 指令放置位置
  • ✅ 伺服器操作非同步函式
  • ✅ 圖片最佳化
  • ✅ 動態路由中的中繼資料
  • ✅ 大量元件的動態匯入
  • ✅ 擷取快取策略
  • ✅ 路由區段設定

摘要

這項技能確保你:

  1. 選擇正確的元件類型(伺服器 vs 客戶端)
  2. 實作適當的資料擷取模式
  3. 使用適當的快取策略
  4. 正確處理伺服器操作
  5. 最佳化中繼資料與 SEO
  6. 避免常見的 Next.js 錯誤
  7. 遵循 Quetrex 的架構準則

如有疑問:

  • 閱讀特定指南(上方連結)
  • 執行驗證器
  • 查閱官方 Next.js 15 文件
  • 預設使用伺服器元件

最後更新:2025-11-23 Next.js 版本:15.5 範例總數:150+ 總行數:4,000+

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能