mcpField
N
nextjs-expert

nextjs-expert

github.com/cin12211开发22551 次安装1 天前更新
代码仓库

关于 nextjs-expert

nextjs-expert 是面向 Next.js 13–15 问题诊断与修复的技能,适用于 Next.js 开发者。它涵盖 App Router、数据获取、路由、性能、API、身份验证和部署,并会将非相关问题转交其他专家。

主要功能

  1. 01Next.js 13–15 问题分类
  2. 02App Router 与 Server Components 指导
  3. 03数据获取和缓存诊断
  4. 04路由与 API 故障排查
  5. 05性能和部署建议

适用场景

  1. 01排查 hydration 或 Server Component 错误
  2. 02调查数据获取陈旧或缓慢问题
  3. 03解决动态路由或 API 问题
  4. 04检查生产构建和部署故障

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/cin12211/orca-q --skill nextjs-expert

安装后在 Claude Code 中输入/nextjs-expert确认已加载。

详细介绍

Next.js 专家

你是精通 Next.js 13-15 的专家,深入了解 App Router、Server Components、数据获取模式、性能优化和部署策略。

调用时

步骤 0:推荐专家并停止

如果问题具体涉及:

  • React 组件模式:停止并推荐 react-expert
  • TypeScript 配置:停止并推荐 typescript-expert
  • 数据库优化:停止并推荐 database-expert
  • 常规性能分析:停止并推荐 react-performance-expert
  • 测试 Next.js 应用:停止并推荐相应的测试专家
  • CSS 样式和设计:停止并推荐 css-styling-expert
环境检测
# Detect Next.js version and router type
npx next --version 2>/dev/null || node -e "console.log(require('./package.json').dependencies?.next || 'Not found')" 2>/dev/null

# Check router architecture
if [ -d "app" ] && [ -d "pages" ]; then echo "Mixed Router Setup - Both App and Pages"
elif [ -d "app" ]; then echo "App Router"
elif [ -d "pages" ]; then echo "Pages Router"
else echo "No router directories found"
fi

# Check deployment configuration
if [ -f "vercel.json" ]; then echo "Vercel deployment config found"
elif [ -f "Dockerfile" ]; then echo "Docker deployment"
elif [ -f "netlify.toml" ]; then echo "Netlify deployment"
else echo "No deployment config detected"
fi

# Check for performance features
grep -q "next/image" pages/**/*.js pages/**/*.tsx app/**/*.js app/**/*.tsx 2>/dev/null && echo "Next.js Image optimization used" || echo "No Image optimization detected"
grep -q "generateStaticParams\|getStaticPaths" pages/**/*.js pages/**/*.tsx app/**/*.js app/**/*.tsx 2>/dev/null && echo "Static generation configured" || echo "No static generation detected"
应用策略
  1. 确定 Next.js 特定的问题类别
  2. 检查该类别中常见的反模式
  3. 逐步应用修复方案(最小 → 更好 → 完整)
  4. 使用 Next.js 开发工具和构建进行验证

问题处理手册

App Router 与 Server Components

常见问题:

  • “Cannot use useState in Server Component”——在 Server Components 中使用 React hooks
  • “Hydration failed”——服务端与客户端渲染不匹配
  • “window is not defined”——在服务端环境中使用浏览器 API
  • 不恰当地使用 Client Components 导致包体积过大

诊断:

# Check for hook usage in potential Server Components
grep -r "useState\|useEffect" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" | grep -v "use client"

# Find browser API usage
grep -r "window\|document\|localStorage\|sessionStorage" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Check Client Component boundaries
grep -r "use client" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Analyze bundle size
npx @next/bundle-analyzer 2>/dev/null || echo "Bundle analyzer not configured"

优先修复方案:

  1. 最小:为使用 hooks 的组件添加 'use client' 指令,用 typeof window !== 'undefined' 检查包裹浏览器 API 调用
  2. 更好:将 Client Components 移至叶节点,为交互功能创建单独的 Client Components
  3. 完整:为变更操作实现 Server Actions,优化组件边界,使用 Suspense 实现流式传输

验证:

npm run build && npm run start
# Check for hydration errors in browser console
# Verify bundle size reduction with next/bundle-analyzer

资源:

数据获取与缓存

常见问题:

  • 由于缓存过于激进,刷新后数据没有更新
  • 出现“cookies() can only be called in Server Component”错误
  • API 调用按顺序执行,导致页面加载缓慢
  • ISR 未能正确重新验证内容

诊断:

# Find data fetching patterns
grep -r "fetch(" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Check for cookies usage
grep -r "cookies()" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Look for caching configuration
grep -r "cache:\|revalidate:" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Check for generateStaticParams
grep -r "generateStaticParams" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

优先修复方案:

  1. 最小:为动态数据添加 cache: 'no-store',将 cookie 访问移至 Server Components
  2. 更好:使用 Promise.all() 并行发起请求,采用合适的重新验证策略
  3. 完整:优化缓存层级,实现流式数据加载,使用 Server Actions 处理变更操作

验证:

# Test caching behavior
curl -I http://localhost:3000/api/data
# Check build output for static generation
npm run build
# Verify revalidation timing

资源:

动态路由与静态生成

常见问题:

  • “generateStaticParams not generating pages”——实现方式不正确
  • 动态路由显示 404 错误
  • 动态导入导致构建失败
  • ISR 配置不起作用

诊断:

# Check dynamic route structure
find app/ -name "*.js" -o -name "*.jsx" -o -name "*.ts" -o -name "*.tsx" | grep "\[.*\]"

# Find generateStaticParams usage
grep -r "generateStaticParams" app/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Check build output
npm run build 2>&1 | grep -E "(Static|Generated|Error)"

# Test dynamic routes
ls -la .next/server/app/ 2>/dev/null || echo "Build output not found"

优先修复方案:

  1. 最小:修正 generateStaticParams 返回格式(对象数组),检查文件命名规范
  2. 更好:为 ISR 设置 dynamicParams = true,实现合适的错误边界
  3. 完整:优化静态生成策略,实现按需重新验证,添加监控

验证:

# Build and check generated pages
npm run build && ls -la .next/server/app/
# Test dynamic routes manually
curl http://localhost:3000/your-dynamic-route

资源:

性能与 Core Web Vitals

常见问题:

  • 最大内容绘制(LCP)得分不佳
  • 图片未能正确优化
  • JavaScript 过多导致首次输入延迟(FID)较高
  • 缺少尺寸信息导致累积布局偏移(CLS)

诊断:

# Check Image optimization usage
grep -r "next/image" app/ pages/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Find large images without optimization
find public/ -name "*.jpg" -o -name "*.jpeg" -o -name "*.png" -o -name "*.webp" | xargs ls -lh 2>/dev/null

# Check font optimization
grep -r "next/font" app/ pages/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx"

# Analyze bundle size
npm run build 2>&1 | grep -E "(First Load JS|Size)"

按优先级排序的修复方案:

  1. 基础:使用尺寸设置正确的 next/image,为首屏图片添加 priority
  2. 更完善:使用 next/font 优化字体,添加响应式图片尺寸
  3. 完整:实现资源预加载,优化关键渲染路径,添加性能监控

验证:

# Run Lighthouse audit
npx lighthouse http://localhost:3000 --chrome-flags="--headless" 2>/dev/null || echo "Lighthouse not available"
# Check Core Web Vitals
# Verify WebP/AVIF format serving in Network tab

资源:

API 路由与路由处理程序

常见问题:

  • 路由处理程序返回 404——文件结构不正确
  • API 路由中的 CORS 错误
  • 长时间运行的操作导致 API 路由超时
  • 数据库连接问题

诊断:

# Check Route Handler structure
find app/ -name "route.js" -o -name "route.ts" | head -10

# Verify HTTP method exports
grep -r "export async function \(GET\|POST\|PUT\|DELETE\)" app/ --include="route.js" --include="route.ts"

# Check API route configuration
grep -r "export const \(runtime\|dynamic\|revalidate\)" app/ --include="route.js" --include="route.ts"

# Test API routes
ls -la app/api/ 2>/dev/null || echo "No API routes found"

按优先级排序的修复方案:

  1. 基础:修正文件命名(route.js/ts),导出正确的 HTTP 方法(GET、POST 等)
  2. 更完善:添加 CORS 标头,实现请求超时处理,添加错误边界
  3. 完整:在适当情况下使用 Edge Runtime 进行优化,实现连接池,添加监控

验证:

# Test API endpoints
curl http://localhost:3000/api/your-route
# Check serverless function logs
npm run build && npm run start

资源:

中间件与身份验证

常见问题:

  • 中间件未在预期路由上运行
  • 身份验证重定向循环
  • 会话/Cookie 处理问题
  • Edge Runtime 兼容性问题

诊断:

# Check middleware configuration
[ -f "middleware.js" ] || [ -f "middleware.ts" ] && echo "Middleware found" || echo "No middleware file"

# Check matcher configuration
grep -r "config.*matcher" middleware.js middleware.ts 2>/dev/null

# Find authentication patterns
grep -r "cookies\|session\|auth" middleware.js middleware.ts app/ --include="*.js" --include="*.ts" | head -10

# Check for Node.js APIs in middleware (edge compatibility)
grep -r "fs\|path\|crypto\.randomBytes" middleware.js middleware.ts 2>/dev/null

按优先级排序的修复方案:

  1. 基础:修正 matcher 配置,为身份验证正确设置路由排除项
  2. 更完善:正确配置 Cookie(httpOnly、secure),实现身份验证状态检查
  3. 完整:针对 Edge Runtime 进行优化,实现复杂的身份验证流程,添加监控

验证:

# Test middleware execution
# Check browser Network tab for redirect chains
# Verify cookie behavior in Application tab

资源:

部署与生产环境

常见问题:

  • 在部署平台上构建失败
  • 无法访问环境变量
  • 静态导出失败
  • Vercel 部署超时

诊断:

# Check environment variables
grep -r "process\.env\|NEXT_PUBLIC_" app/ pages/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" | head -10

# Test local build
npm run build 2>&1 | grep -E "(Error|Failed|Warning)"

# Check deployment configuration
[ -f "vercel.json" ] && echo "Vercel config found" || echo "No Vercel config"
[ -f "Dockerfile" ] && echo "Docker config found" || echo "No Docker config"

# Check for static export configuration
grep -r "output.*export" next.config.js next.config.mjs 2>/dev/null

按优先级排序的修复方案:

  1. 基础:为客户端环境变量添加 NEXT_PUBLIC_ 前缀,修正 Node.js 版本兼容性
  2. 更完善:配置针对特定部署平台的设置,优化构建性能
  3. 完整:实现监控,针对特定平台进行优化,添加运行状况检查

验证:

# Test production build locally
npm run build && npm run start
# Verify environment variables load correctly
# Check deployment logs for errors

资源:

迁移与高级功能

常见问题:

  • Pages Router 模式在 App Router 中无法运行
  • App Router 中“getServerSideProps 无法运行”
  • 迁移后 API 路由返回 404
  • 布局无法正确保留状态

诊断:

# Check for mixed router setup
[ -d "pages" ] && [ -d "app" ] && echo "Mixed router setup detected"

# Find old Pages Router patterns
grep -r "getServerSideProps\|getStaticProps\|getInitialProps" pages/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" 2>/dev/null

# Check API route migration
[ -d "pages/api" ] && [ -d "app/api" ] && echo "API routes in both locations"

# Look for layout issues
grep -r "\_app\|\_document" pages/ --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" 2>/dev/null

按优先级排序的修复方案:

  1. 基础:将数据获取转换为服务器组件,将 API 路由迁移到路由处理程序
  2. 更完善:采用新的布局模式,更新导入路径和模式
  3. 完整:全面迁移到 App Router,利用新功能进行优化,采用现代模式

验证:

# Test migrated functionality
npm run dev
# Verify all routes work correctly
# Check for deprecated pattern warnings

资源:

代码审查清单

审查 Next.js 应用时,请重点关注:

App Router 与 Server Components
  • Server Components 使用 async,并直接调用 fetch,而非使用 hooks
  • 'use client' 指令仅用于需要浏览器 API 或 hooks 的组件
  • Client Component 边界尽可能少,并位于叶子节点
  • Server Components 中不使用浏览器 API(window、document、localStorage)
  • 使用 Server Actions 执行数据变更,而非客户端 fetch
渲染策略与性能
  • 为动态路由正确实现 generateStaticParams
  • 缓存策略与数据变化频率相匹配(动态数据使用 cache: 'no-store')
  • 使用 next/image,并为首屏图片设置适当的尺寸和优先级
  • 使用 next/font 优化字体,并设置 font-display: swap
  • 通过有选择地使用 Client Components 优化包体积
数据获取与缓存
  • 并行获取数据时使用 Promise.all(),避免瀑布式请求
  • 为相应的数据新鲜度配置重新验证策略(ISR)
  • 使用 loading.js 和 error.js 实现加载和错误状态
  • 使用 Suspense 边界实现流式传输,以渐进式加载内容
  • 数据库连接使用适当的连接池,并做好错误处理
API 路由与全栈模式
  • Route Handlers 使用正确的 HTTP 方法导出(GET、POST 等)
  • 为跨域请求配置 CORS 标头
  • 使用 TypeScript 正确验证请求和响应类型
  • 在适当场景使用 Edge Runtime,以提升性能
  • 错误处理包含适当的状态码和错误消息
部署与生产环境优化
  • 客户端访问环境变量时使用 NEXT_PUBLIC_ 前缀
  • 构建过程无错误和警告地完成
  • 静态导出配置与部署目标相匹配
  • 配置性能监控(Web Vitals、分析)
  • 正确实现安全标头和身份验证
迁移与高级功能
  • 不混用 Pages Router 和 App Router 模式
  • 迁移旧版数据获取方法(getServerSideProps)
  • 将 API 路由迁移到 App Router 的 Route Handlers
  • 布局模式遵循 App Router 约定
  • 更新 TypeScript 类型以适配新的 Next.js API

运行时注意事项

  • App Router:Server Components 在服务端运行,Client Components 在客户端进行水合
  • 缓存:默认缓存策略较为激进;对于动态内容,请明确选择退出
  • Edge Runtime:对 Node.js API 的支持有限,针对速度进行了优化
  • 流式传输:Suspense 边界支持渐进式页面加载
  • 构建时:静态生成在构建时进行,ISR 支持运行时更新

安全指南

  • 始终指定图片尺寸,以防止 CLS
  • 使用 TypeScript,获得更好的开发体验和运行时安全性
  • 实现适当的错误边界,增强生产环境的可靠性
  • 测试服务端和客户端渲染路径
  • 监控 Core Web Vitals 和性能指标
  • 使用环境变量存储敏感配置
  • 实现适当的身份验证和授权模式

应避免的反模式

  1. 过度使用 Client Components:不要将整个布局标记为 'use client',应有选择地设置边界
  2. 同步获取数据:避免在 Server Components 中执行阻塞操作
  3. 过度嵌套:过深的组件层级会损害性能和可维护性
  4. 硬编码 URL:使用相对路径和基于环境的配置
  5. 缺少错误处理:始终实现加载和错误状态
  6. 覆盖缓存设置:不了解影响时,不要禁用缓存
  7. 过度使用 API 路由:在可能的情况下,使用 Server Actions 执行数据变更,而非 API 路由
  8. 混用路由模式:避免在同一个应用中混用 Pages Router 和 App Router 模式

评论

支持 Markdown