Communitygithub.com

Samueladewole/claude-skills

精通 Next.js 14+ App Router、伺服器元件、串流、平行路由與進階資料擷取。在建構 Next.js 應用程式、實作 SSR/SSG 或最佳化 React 伺服器元件時使用。

claude-skills 是什麼?

此技能提供了一套全面的 Next.js 14+ App Router 架構模式,專為開發者在使用現代全端 React 開發時所設計。它涵蓋了伺服器元件、客戶端元件、串流、平行路由、攔截路由、伺服器動作和路由處理常式等核心概念。此技能適用於所有支援 AI 代理的開發工具,如 Claude Code、Cursor 或 Codex。透過實作範例和最佳實務,使用者可以學習如何有效地建立具備 SSR/SSG、ISR 和進階資料快取策略的高效能 Next.js 應用程式。它還詳細解釋了檔案慣例、中繼資料與 SEO 設定,以及如何利用 Suspense 進行漸進式串流渲染。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Samueladewole/claude-skills/tree/HEAD/nextjs-app-router-patterns

在你喜歡的 AI 中提問

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

說明文件

Next.js App Router 模式

適用於 Next.js 14+ App Router 架構、伺服器元件與現代全端 React 開發的全面模式。

何時使用此技能

  • 使用 App Router 建構新的 Next.js 應用程式
  • 從 Pages Router 遷移至 App Router
  • 實作伺服器元件與串流
  • 設定平行與攔截路由
  • 最佳化資料擷取與快取
  • 使用伺服器動作建構全端功能

核心概念

1. 渲染模式

模式渲染位置使用時機
伺服器元件僅限伺服器資料擷取、大量運算、機密資訊
客戶端元件瀏覽器互動性、鉤子、瀏覽器 API
靜態建置時間極少變更的內容
動態請求時間個人化或即時資料
串流漸進式大型頁面、緩慢的資料來源

2. 檔案慣例

app/
├── layout.tsx       # 共享 UI 包裝器
├── page.tsx         # 路由 UI
├── loading.tsx      # 載入 UI(Suspense)
├── error.tsx        # 錯誤邊界
├── not-found.tsx    # 404 UI
├── route.ts         # API 端點
├── template.tsx     # 重新掛載的佈局
├── default.tsx      # 平行路由的備用方案
└── opengraph-image.tsx  # OG 圖片生成

快速開始

// app/layout.tsx
import { Inter } from 'next/font/google'
import { Providers } from './providers'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: { default: 'My App', template: '%s | My App' },
  description: 'Built with Next.js App Router',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body className={inter.className}>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}

// app/page.tsx - 預設為伺服器元件
async function getProducts() {
  const res = await fetch('https://api.example.com/products', {
    next: { revalidate: 3600 }, // ISR:每小時重新驗證
  })
  return res.json()
}

export default async function HomePage() {
  const products = await getProducts()

  return (
    <main>
      <h1>Products</h1>
      <ProductGrid products={products} />
    </main>
  )
}

模式

模式 1:使用資料擷取的伺服器元件

// app/products/page.tsx
import { Suspense } from 'react'
import { ProductList, ProductListSkeleton } from '@/components/products'
import { FilterSidebar } from '@/components/filters'

interface SearchParams {
  category?: string
  sort?: 'price' | 'name' | 'date'
  page?: string
}

export default async function ProductsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const params = await searchParams

  return (
    <div className="flex gap-8">
      <FilterSidebar />
      <Suspense
        key={JSON.stringify(params)}
        fallback={<ProductListSkeleton />}
      >
        <ProductList
          category={params.category}
          sort={params.sort}
          page={Number(params.page) || 1}
        />
      </Suspense>
    </div>
  )
}

// components/products/ProductList.tsx - 伺服器元件
async function getProducts(filters: ProductFilters) {
  const res = await fetch(
    `${process.env.API_URL}/products?${new URLSearchParams(filters)}`,
    { next: { tags: ['products'] } }
  )
  if (!res.ok) throw new Error('Failed to fetch products')
  return res.json()
}

export async function ProductList({ category, sort, page }: ProductFilters) {
  const { products, totalPages } = await getProducts({ category, sort, page })

  return (
    <div>
      <div className="grid grid-cols-3 gap-4">
        {products.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>
      <Pagination currentPage={page} totalPages={totalPages} />
    </div>
  )
}

模式 2:使用 'use client' 的客戶端元件

// components/products/AddToCartButton.tsx
'use client'

import { useState, useTransition } from 'react'
import { addToCart } from '@/app/actions/cart'

export function AddToCartButton({ productId }: { productId: string }) {
  const [isPending, startTransition] = useTransition()
  const [error, setError] = useState<string | null>(null)

  const handleClick = () => {
    setError(null)
    startTransition(async () => {
      const result = await addToCart(productId)
      if (result.error) {
        setError(result.error)
      }
    })
  }

  return (
    <div>
      <button
        onClick={handleClick}
        disabled={isPending}
        className="btn-primary"
      >
        {isPending ? 'Adding...' : 'Add to Cart'}
      </button>
      {error && <p className="text-red-500 text-sm">{error}</p>}
    </div>
  )
}

模式 3:伺服器動作

// app/actions/cart.ts
"use server";

import { revalidateTag } from "next/cache";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export async function addToCart(productId: string) {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get("session")?.value;

  if (!sessionId) {
    redirect("/login");
  }

  try {
    await db.cart.upsert({
      where: { sessionId_productId: { sessionId, productId } },
      update: { quantity: { increment: 1 } },
      create: { sessionId, productId, quantity: 1 },
    });

    revalidateTag("cart");
    return { success: true };
  } catch (error) {
    return { error: "Failed to add item to cart" };
  }
}

export async function checkout(formData: FormData) {
  const address = formData.get("address") as string;
  const payment = formData.get("payment") as string;

  // 驗證
  if (!address || !payment) {
    return { error: "Missing required fields" };
  }

  // 處理訂單
  const order = await processOrder({ address, payment });

  // 重新導向至確認頁面
  redirect(`/orders/${order.id}/confirmation`);
}

模式 4:平行路由

// app/dashboard/layout.tsx
export default function DashboardLayout({
  children,
  analytics,
  team,
}: {
  children: React.ReactNode
  analytics: React.ReactNode
  team: React.ReactNode
}) {
  return (
    <div className="dashboard-grid">
      <main>{children}</main>
      <aside className="analytics-panel">{analytics}</aside>
      <aside className="team-panel">{team}</aside>
    </div>
  )
}

// app/dashboard/@analytics/page.tsx
export default async function AnalyticsSlot() {
  const stats = await getAnalytics()
  return <AnalyticsChart data={stats} />
}

// app/dashboard/@analytics/loading.tsx
export default function AnalyticsLoading() {
  return <ChartSkeleton />
}

// app/dashboard/@team/page.tsx
export default async function TeamSlot() {
  const members = await getTeamMembers()
  return <TeamList members={members} />
}

模式 5:攔截路由(Modal 模式)

// 照片 Modal 的檔案結構
// app/
// ├── @modal/
// │   ├── (.)photos/[id]/page.tsx  # 攔截
// │   └── default.tsx
// ├── photos/
// │   └── [id]/page.tsx            # 完整頁面
// └── layout.tsx

// app/@modal/(.)photos/[id]/page.tsx
import { Modal } from '@/components/Modal'
import { PhotoDetail } from '@/components/PhotoDetail'

export default async function PhotoModal({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const photo = await getPhoto(id)

  return (
    <Modal>
      <PhotoDetail photo={photo} />
    </Modal>
  )
}

// app/photos/[id]/page.tsx - 完整頁面版本
export default async function PhotoPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  const photo = await getPhoto(id)

  return (
    <div className="photo-page">
      <PhotoDetail photo={photo} />
      <RelatedPhotos photoId={id} />
    </div>
  )
}

// app/layout.tsx
export default function RootLayout({
  children,
  modal,
}: {
  children: React.ReactNode
  modal: React.ReactNode
}) {
  return (
    <html>
      <body>
        {children}
        {modal}
      </body>
    </html>
  )
}

模式 6:使用 Suspense 的串流

// app/product/[id]/page.tsx
import { Suspense } from 'react'

export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params

  // 此資料優先載入(阻斷性)
  const product = await getProduct(id)

  return (
    <div>
      {/* 立即渲染 */}
      <ProductHeader product={product} />

      {/* 串流載入評論 */}
      <Suspense fallback={<ReviewsSkeleton />}>
        <Reviews productId={id} />
      </Suspense>

      {/* 串流載入推薦 */}
      <Suspense fallback={<RecommendationsSkeleton />}>
        <Recommendations productId={id} />
      </Suspense>
    </div>
  )
}

// 這些元件各自擷取自己的資料
async function Reviews({ productId }: { productId: string }) {
  const reviews = await getReviews(productId) // 慢速 API
  return <ReviewList reviews={reviews} />
}

async function Recommendations({ productId }: { productId: string }) {
  const products = await getRecommendations(productId) // 基於 ML,速度慢
  return <ProductCarousel products={products} />
}

模式 7:路由處理常式(API 路由)

// app/api/products/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const category = searchParams.get("category");

  const products = await db.product.findMany({
    where: category ? { category } : undefined,
    take: 20,
  });

  return NextResponse.json(products);
}

export async function POST(request: NextRequest) {
  const body = await request.json();

  const product = await db.product.create({
    data: body,
  });

  return NextResponse.json(product, { status: 201 });
}

// app/api/products/[id]/route.ts
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const product = await db.product.findUnique({ where: { id } });

  if (!product) {
    return NextResponse.json({ error: "Product not found" }, { status: 404 });
  }

  return NextResponse.json(product);
}

模式 8:中繼資料與 SEO

// app/products/[slug]/page.tsx
import { Metadata } from 'next'
import { notFound } from 'next/navigation'

type Props = {
  params: Promise<{ slug: string }>
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params
  const product = await getProduct(slug)

  if (!product) return {}

  return {
    title: product.name,
    description: product.description,
    openGraph: {
      title: product.name,
      description: product.description,
      images: [{ url: product.image, width: 1200, height: 630 }],
    },
    twitter: {
      card: 'summary_large_image',
      title: product.name,
      description: product.description,
      images: [product.image],
    },
  }
}

export async function generateStaticParams() {
  const products = await db.product.findMany({ select: { slug: true } })
  return products.map((p) => ({ slug: p.slug }))
}

export default async function ProductPage({ params }: Props) {
  const { slug } = await params
  const product = await getProduct(slug)

  if (!product) notFound()

  return <ProductDetail product={product} />
}

快取策略

資料快取

// 無快取(始終保持最新)
fetch(url, { cache: "no-store" });

// 永遠快取(靜態)
fetch(url, { cache: "force-cache" });

// ISR - 60 秒後重新驗證
fetch(url, { next: { revalidate: 60 } });

// 基於標籤的失效
fetch(url, { next: { tags: ["products"] } });

// 透過伺服器動作失效
("use server");
import { revalidateTag, revalidatePath } from "next/cache";

export async function updateProduct(id: string, data: ProductData) {
  await db.product.update({ where: { id }, data });
  revalidateTag("products");
  revalidatePath("/products");
}

最佳實務

應做的事項

  • 從伺服器元件開始 - 僅在需要時才添加 'use client'
  • 將資料擷取與使用位置放在一起 - 在使用資料的地方進行擷取
  • 使用 Suspense 邊界 - 為慢速資料啟用串流
  • 利用平行路由 - 獲得獨立的載入狀態
  • 使用伺服器動作 - 進行具備漸進增強的突變操作

避免的事項

  • 不要傳遞不可序列化的資料 - 伺服器 → 客戶端邊界限制
  • 不要在伺服器元件中使用鉤子 - 不使用 useState、useEffect
  • 不要在客戶端元件中進行資料擷取 - 使用伺服器元件或 React Query
  • 不要過度巢狀佈局 - 每個佈局都會增加元件樹
  • 不要忽略載入狀態 - 始終提供 loading.tsx 或 Suspense

資源

Individual skills in this repo

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

Samueladewole/claude-skills

Create API handoff documentation for frontend developers. Use when backend work is complete and needs to be documented for frontend integration, or user says 'create handoff', 'document API', 'frontend handoff', or 'API documentation'.

Samueladewole/claude-skills

Set up Tailwind CSS v4 in Expo with react-native-css and NativeWind v5 for universal styling

Samueladewole/claude-skills

Build accessible, responsive, and performant frontend components with design system best practices, modern CSS, and framework-agnostic patterns.

Samueladewole/claude-skills

Document frontend data needs for backend developers. Use when frontend needs to communicate API requirements to backend, or user says 'backend requirements', 'what data do I need', 'API requirements', or is describing data needs for a UI.

Samueladewole/claude-skills

Comprehensive skill for GSAP (GreenSock Animation Platform) and ScrollTrigger plugin. Use this skill when creating web animations, scroll-driven experiences, timelines, tweens, scroll-triggered animations, pinning, scrubbing, parallax effects, or animating DOM elements, SVG, Canvas, WebGL, or Three.js. Triggers on tasks involving GSAP, ScrollTrigger, smooth animations, scroll effects, or animation sequencing.

Samueladewole/claude-skills

Build scalable design systems with Tailwind CSS, design tokens, component libraries, and responsive patterns. Use when creating component libraries, implementing design systems, or standardizing UI patterns.

Samueladewole/claude-skills

Analyze a short-form video (TikTok, Instagram Reel, YouTube Short, or any MP4) to extract its full transcript, understand why it performed, and generate concrete repurposing ideas. Use this skill whenever the user asks to: analyze a video, understand why something went viral, reverse-engineer a creator's content, extract a transcript from a video, figure out what makes a video perform, or get repurposing ideas from a video. Also trigger when the user says things like "why did this perform", "what's the hook here", "can I repurpose this", "analyze this TikTok/Reel", or drops a video file path or URL.

相關技能