Communitygithub.com

sakilanwar12/nextjs-typescript-skills

在 Next.js App Router 中擷取資料時使用 — 包含 RSC 擷取、快取、重新驗證、Suspense 串流、平行擷取或路由處理器。確保正確的快取與瀑布流行為。

nextjs-typescript-skills 是什麼?

這個技能為 Next.js App Router 的資料擷取提供了準則與模式,協助開發者避免常見的效能陷阱,例如不必要的瀑布流請求或錯誤的快取設定。它支援在伺服器元件中使用 async/await 進行擷取、透過 `cache` 與 `next.revalidate` 控制快取行為、使用 `Promise.all` 平行化獨立請求,以及透過 `<Suspense>` 與 `loading.tsx` 啟用串流。此外,這項技能也示範了如何利用 `revalidateTag` 進行隨選重新驗證,以及何時應(或不應)在客戶端使用 SWR 或 React Query。這些模式普遍適用於 Next.js 13+ 的路由處理器與伺服器元件,確保快取語意與資料依賴關係正確無誤。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/sakilanwar12/nextjs-typescript-skills/tree/HEAD/skills/nextjs-data-fetching

在你喜歡的 AI 中提問

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

說明文件

Next.js 資料擷取

規則

  1. 在伺服器元件中使用 async/await 擷取資料。不要使用 useEffect 處理初始資料。
  2. fetch() 在 App Router 中預設是快取的,除非加上 { cache: 'no-store' } 或 next: { revalidate } 參數。請務必清楚你要哪一種行為。
  3. 使用 Promise.all 平行化獨立的請求。只有依賴性的請求才依序執行。
  4. 將較慢的區塊包在 <Suspense fallback> 加上 loading.tsx 中以實現串流。
  5. 使用 next: { tags: ['posts'] } 搭配 revalidateTag('posts') 進行隨選失效。
  6. 僅在互動式/過濾式 UI 中才使用客戶端擷取(SWR/React Query)——不要用於首次畫面呈現。

範例模式

// 靜態資料搭配重新驗證 (ISR)
async function getPosts() {
  const res = await fetch('https://api.example.com/posts', {
    next: { revalidate: 60 },
  });
  if (!res.ok) throw new Error('無法擷取文章');
  return res.json();
}

// 動態資料,永不快取
async function getInbox(userId: string) {
  const res = await fetch(`https://api.example.com/inbox/${userId}`, {
    cache: 'no-store',
  });
  return res.json();
}

// 在伺服器元件中平行擷取
export default async function Dashboard() {
  const [user, posts] = await Promise.all([getUser(), getPosts()]);
  return <View user={user} posts={posts} />;
}

// 串流一個較慢的區段
import { Suspense } from 'react';
export default function Page() {
  return (
    <div>
      <FastHeader />
      <Suspense fallback={<CommentsSkeleton />}>
        <SlowComments />
      </Suspense>
    </div>
  );
}
// app/api/revalidate/route.ts — 隨選重新驗證
import { revalidateTag } from 'next/cache';
export async function POST(req: Request) {
  const { tag, secret } = await req.json();
  if (secret !== process.env.REVALIDATE_SECRET)
    return Response.json({ ok: false }, { status: 401 });
  revalidateTag(tag);
  return Response.json({ ok: true });
}

檢查清單

  • 使用伺服器元件擷取,而不是 useEffect?
  • 快取模式已明確指定(revalidate、no-store 或 tags)?
  • 獨立請求已平行化?
  • 為較慢的部分加上 Suspense 邊界?
  • 錯誤已處理(拋出 → error.tsx,或優雅降級)?

Individual skills in this repo

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

相關技能