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 开发场景设计。它包含 150+ 个代码示例和 4000+ 行代码,覆盖了从文件路由、数据获取、缓存策略到服务器操作、元数据 API 等所有关键主题。该技能通过严格的规则(如强制使用 `<Image>` 而不是 `<img>`,服务端组件为默认模式)和决策树帮助开发者避免常见错误,确保代码正确性和构建稳定性。支持使用 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 专家技能 是做什么的?

适用于 Quetrex 开发的完整 Next.js 15 参考。

该技能提供关于所有 Next.js 15 App Router 模式的全面指导,确保代理能够第一次就正确实现现代 Next.js。


关键规则(绝不能违反)

以下规则是不可协商的。违反将导致构建失败。

1. 始终使用 <Image> 来自 next/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 图像组件提供自动优化、延迟加载并防止布局偏移。ESLint 配置为在 <img> 使用时使构建失败。

2. 服务端组件是默认选项 —— 只在需要时添加 'use client'

3. 绝不能创建异步客户端组件

4. 始终为 fetch() 指定缓存策略


何时使用此技能

在以下情况下使用此技能:

  • 创建新路由或页面
  • 实现数据获取(服务端组件 vs 客户端组件)
  • 服务端 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 结构化数据
  • 视口配置
  • PWA 清单
  • Robots.txt
  • 站点地图生成

✅ 模式验证器

可执行的 Python 脚本,检查:

  • 服务端组件不使用客户端专用 API
  • 客户端组件具有 'use client' 指令
  • 数据获取使用正确的缓存策略
  • 服务器操作标记为 'use server'
  • 正确使用元数据 API
  • 图像优化( 而非 )
  • 对重量级组件使用动态导入

运行:python validate-patterns.py /path/to/src


快速参考

服务端 vs 客户端组件决策树

你是否需要交互性(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}>
        删除
      </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">创建</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>出了点问题!</h2>
      <button onClick={reset}>重试</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 src="/logo.png" alt="Logo" width={200} height={100} />

故障排除

错误:“你正在导入一个需要 useState 的组件...”

解决方法: 向组件文件添加 'use client'。

错误:“async/await 在客户端组件中无效”

解决方法: 移除 'use client' 或使用 useEffect 替代 async 组件。

错误:“process 未定义”

解决方法: 客户端组件中的环境变量需要 NEXT_PUBLIC_ 前缀。

错误:“Headers 已发送”

解决方法: 在发送响应后不要使用 headers() 或 cookies()。在任何流式传输之前调用它们。


官方文档


验证

运行模式验证器检查您的代码:

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

验证器检查:

  • ✅ 异步客户端组件(禁止)
  • ✅ 服务端组件中的客户端 API
  • ✅ 'use client' 指令位置
  • ✅ 服务器操作异步函数
  • ✅ 图像优化
  • ✅ 动态路由中的元数据
  • ✅ 对重量级组件使用动态导入
  • ✅ Fetch 缓存策略
  • ✅ 路由段配置

总结

此技能确保您:

  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

相关技能