nextjs-expert について
nextjs-expertは、Next.js 13~15の問題を診断・解決するスキルです。Next.js開発者向けに、App Router、データ取得、ルーティング、パフォーマンス、API、認証、デプロイを扱い、対象外の問題は他の専門スキルに案内します。
主な機能
- 01Next.js 13~15の問題分類
- 02App RouterとServer Componentsの案内
- 03データ取得とキャッシュの診断
- 04ルーティングとAPIのトラブル対応
- 05パフォーマンスとデプロイの助言
活用シーン
- 01hydrationやServer Componentのエラー調査
- 02データ取得の陳腐化や遅延の調査
- 03動的ルートやAPIの問題解決
- 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"
戦略の適用
- Next.js 固有の問題カテゴリを特定します
- そのカテゴリでよくあるアンチパターンを確認します
- 段階的に修正します(最小限 → より良い方法 → 完全な対応)
- Next.js の開発ツールとビルドで検証します
問題別プレイブック
App Router と Server Components
よくある問題:
- 「Cannot use useState in Server Component」 - Server Components での React フック
- 「Hydration failed」 - サーバーとクライアントのレンダリングの不一致
- 「window is not defined」 - サーバー環境でのブラウザー API
- Client Component の不適切な使用によるバンドルサイズの増大
診断:
# 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"
優先順位を付けた修正:
- 最小限:フックを使用するコンポーネントに 'use client' ディレクティブを追加し、ブラウザー API の呼び出しを
typeof window !== 'undefined'チェックで囲みます - より良い方法:Client Components をリーフノードに移動し、インタラクティブな機能には個別の Client Components を作成します
- 完全な対応:変更処理に Server Actions を実装し、コンポーネントの境界を最適化して、Suspense でストリーミングを使用します
検証:
npm run build && npm run start
# Check for hydration errors in browser console
# Verify bundle size reduction with next/bundle-analyzer
リソース:
- https://nextjs.org/docs/app/building-your-application/rendering/client-components
- https://nextjs.org/docs/app/building-your-application/rendering/server-components
- https://nextjs.org/docs/messages/react-hydration-error
データフェッチとキャッシュ
よくある問題:
- キャッシュが強すぎて、更新後もデータが更新されない
- 「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"
優先順位を付けた修正:
- 最小限:動的データに
cache: 'no-store'を追加し、Cookie へのアクセスを Server Components に移動します - より良い方法:
Promise.all()でリクエストを並列化し、適切な再検証戦略を実装します - 完全な対応:キャッシュ階層を最適化し、ストリーミングによるデータ読み込みを実装して、変更処理に Server Actions を使用します
検証:
# Test caching behavior
curl -I http://localhost:3000/api/data
# Check build output for static generation
npm run build
# Verify revalidation timing
リソース:
- https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating
- https://nextjs.org/docs/app/api-reference/functions/cookies
- https://nextjs.org/docs/app/building-your-application/data-fetching/patterns
動的ルートと静的生成
よくある問題:
- 「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"
優先順位を付けた修正:
- 最小限:generateStaticParams の戻り値の形式(オブジェクトの配列)を修正し、ファイル名の規則を確認します
- より良い方法:ISR 用に
dynamicParams = trueを設定し、適切なエラーバウンダリーを実装します - 完全な対応:静的生成戦略を最適化し、オンデマンド再検証を実装して、モニタリングを追加します
検証:
# Build and check generated pages
npm run build && ls -la .next/server/app/
# Test dynamic routes manually
curl http://localhost:3000/your-dynamic-route
リソース:
- https://nextjs.org/docs/app/api-reference/functions/generate-static-params
- https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes
- https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration
パフォーマンスと Core Web Vitals
よくある問題:
- Largest Contentful Paint(LCP)のスコアが低い
- 画像が適切に最適化されていない
- JavaScript の過剰な使用による First Input Delay(FID)の増大
- サイズ指定の欠如による Cumulative Layout Shift(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)"
優先度順の修正方法:
- 最小限:適切なサイズを指定して next/image を使用し、ファーストビュー内の画像に
priorityを追加します - 改善:next/font でフォントを最適化し、レスポンシブ画像のサイズを追加します
- 完全対応:リソースのプリロードを実装し、クリティカルレンダリングパスを最適化して、パフォーマンス監視を追加します
検証:
# 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
参考資料:
- https://nextjs.org/docs/app/building-your-application/optimizing/images
- https://nextjs.org/docs/app/building-your-application/optimizing/fonts
- https://web.dev/vitals/
API ルートと Route Handler
よくある問題:
- Route Handler が 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"
優先度順の修正方法:
- 最小限:ファイル名を修正し(route.js/ts)、適切な HTTP メソッド(GET、POST など)をエクスポートします
- 改善:CORS ヘッダーを追加し、リクエストのタイムアウト処理を実装して、エラーバウンダリーを追加します
- 完全対応:適切な場合は Edge Runtime で最適化し、コネクションプーリングを実装して、監視を追加します
検証:
# Test API endpoints
curl http://localhost:3000/api/your-route
# Check serverless function logs
npm run build && npm run start
参考資料:
- https://nextjs.org/docs/app/building-your-application/routing/route-handlers
- https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
- https://nextjs.org/docs/app/building-your-application/routing/route-handlers#cors
Middleware と認証
よくある問題:
- Middleware が想定したルートで実行されない
- 認証によるリダイレクトループ
- セッション/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
優先度順の修正方法:
- 最小限:matcher の設定を修正し、認証用のルート除外を適切に実装します
- 改善:Cookie を適切に設定し(httpOnly、secure)、認証状態のチェックを実装します
- 完全対応:Edge Runtime 向けに最適化し、高度な認証フローを実装して、監視を追加します
検証:
# Test middleware execution
# Check browser Network tab for redirect chains
# Verify cookie behavior in Application tab
参考資料:
- https://nextjs.org/docs/app/building-your-application/routing/middleware
- https://nextjs.org/docs/app/building-your-application/authentication
- https://nextjs.org/docs/app/api-reference/edge
デプロイと本番環境
よくある問題:
- デプロイプラットフォームでビルドに失敗する
- 環境変数にアクセスできない
- 静的エクスポートに失敗する
- 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
優先度順の修正方法:
- 最小限:クライアント側の環境変数に NEXT_PUBLIC_ プレフィックスを追加し、Node.js のバージョン互換性を修正します
- 改善:デプロイ先固有の設定を行い、ビルドのパフォーマンスを最適化します
- 完全対応:監視を実装し、特定のプラットフォーム向けに最適化して、ヘルスチェックを追加します
検証:
# Test production build locally
npm run build && npm run start
# Verify environment variables load correctly
# Check deployment logs for errors
参考資料:
- https://nextjs.org/docs/app/building-your-application/deploying
- https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
- https://vercel.com/docs/functions/serverless-functions
移行と高度な機能
よくある問題:
- Pages Router のパターンが App Router で動作しない
- App Router で「getServerSideProps が動作しない」
- 移行後に API ルートが 404 を返す
- Layout で状態が適切に保持されない
診断:
# 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
優先度順の修正方法:
- 最小限:データ取得を Server Components に変換し、API ルートを Route Handler に移行します
- 改善:新しいレイアウトパターンを実装し、インポートパスとパターンを更新します
- 完全対応:App Router への完全移行を行い、新機能で最適化して、最新のパターンを実装します
検証:
# Test migrated functionality
npm run dev
# Verify all routes work correctly
# Check for deprecated pattern warnings
参考資料:
- https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration
- https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates
- https://nextjs.org/docs/app/building-your-application/upgrading
コードレビューのチェックリスト
Next.js アプリケーションをレビューする際は、以下に注目してください。
App Router と Server Components
- Server Components は非同期で、フックではなく直接の fetch 呼び出しを使用している
- 'use client' ディレクティブは、ブラウザー API またはフックが必要なコンポーネントにのみ指定されている
- Client Component の境界は最小限で、リーフノードに配置されている
- Server Components でブラウザー API(window、document、localStorage)を使用していない
- ミューテーションには、クライアント側の fetch ではなく Server Actions を使用している
レンダリング戦略とパフォーマンス
- 動的ルートに対して generateStaticParams が適切に実装されている
- キャッシュ戦略がデータの変動性に合っている(動的データには cache: 'no-store' を使用)
- next/image を適切な寸法で使用し、ファーストビュー内の画像には priority を指定している
- フォントの最適化に next/font を使用し、font-display: swap を指定している
- Client Component の使用を選択的にすることで、バンドルサイズを最適化している
データ取得とキャッシュ
- 並列データ取得では 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)を移行している
- App Router では API ルートを Route Handlers に移行している
- レイアウトのパターンが App Router の規約に従っている
- 新しい Next.js API に合わせて TypeScript の型を更新している
ランタイムに関する考慮事項
- App Router:Server Components はサーバー上で実行され、Client Components はクライアント上でハイドレーションされます
- キャッシュ:デフォルトのキャッシュは積極的に行われます。動的コンテンツでは明示的に無効にしてください
- Edge Runtime:Node.js API のサポートは限定的で、速度に最適化されています
- ストリーミング:Suspense 境界によってページを段階的に読み込めます
- ビルド時:静的生成はビルド時に行われ、ISR ではランタイムに更新できます
安全性に関するガイドライン
- CLS を防ぐため、画像の寸法を必ず指定してください
- 開発体験とランタイムの安全性を高めるために TypeScript を使用してください
- 本番環境の耐障害性を高めるため、適切なエラー境界を実装してください
- サーバーとクライアントの両方のレンダリング経路をテストしてください
- Core Web Vitals とパフォーマンス指標を監視してください
- 機密性の高い設定には環境変数を使用してください
- 適切な認証および認可のパターンを実装してください
避けるべきアンチパターン
- Client Component の過剰な使用:レイアウト全体に 'use client' を指定せず、必要な箇所にのみ境界を設けてください
- 同期的なデータ取得:Server Components で処理をブロックする操作は避けてください
- 過剰なネスト:コンポーネント階層が深いと、パフォーマンスと保守性が損なわれます
- URL のハードコード:相対パスと環境に応じた設定を使用してください
- エラーハンドリングの欠如:ローディング状態とエラー状態を必ず実装してください
- キャッシュの上書き:影響を理解せずにキャッシュを無効にしないでください
- API ルートの過剰な使用:可能な場合は、ミューテーションに API ルートではなく Server Actions を使用してください
- ルーターのパターンの混在:同じアプリケーション内で Pages Router と App Router のパターンを混在させないでください
コメント
Markdown 対応