Communitygithub.com

Next.js 最佳實務

遵循 Next.js App Router 原則,包含伺服器元件、資料擷取與路由模式。

Next.js 最佳實務 是什麼?

這個技能提供一套全面的 Next.js App Router 開發最佳實務指南。它涵蓋了從伺服器與用戶端元件選擇、資料擷取策略、檔案約定路由、API 路由處理、效能最佳化(如圖片與捆綁)、中繼資料管理、快取策略,到伺服器動作與反模式等關鍵主題。對於使用 Next.js 13+ App Router 的開發者來說,這是一份寶貴的參考資料,能幫助他們建立高效能、可維護的應用程式。技能文件以結構化表格、決策樹和具體範例呈現,易於遵循且可直接套用於專案中。支援的 AI 平台包括 Claude Code、Cursor 與 Codex 等。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/sickn33/nextjs-best-practices

在你喜歡的 AI 中提問

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

說明文件

Next.js 最佳實務 是做什麼的?

適用於 Next.js App Router 開發的原則。


1. 伺服器與用戶端元件

決策樹

是否需要...?
│
├── useState、useEffect、事件處理器
│   └── 用戶端元件('use client')
│
├── 直接資料擷取,無需互動
│   └── 伺服器元件(預設)
│
└── 兩者都需要?
    └── 拆分:伺服器父元件 + 用戶端子元件

預設用法

類型用途
伺服器資料擷取、佈局、靜態內容
用戶端表單、按鈕、互動式 UI

2. 資料擷取模式

擷取策略

模式用途
預設靜態(建置時快取)
重新驗證ISR(基於時間的重新整理)
不儲存動態(每次請求)

資料流程

來源模式
資料庫伺服器元件擷取
API使用快取的 fetch
使用者輸入客戶端狀態 + 伺服器動作

3. 路由原則

檔案約定

檔案用途
page.tsx路由 UI
layout.tsx共享佈局
loading.tsx載入狀態
error.tsx錯誤邊界
not-found.tsx404 頁面

路由組織

模式用途
路由群組 (name)組織但不影響 URL
並行路由 @slot多個同層級頁面
攔截路由 (.)模態疊層

4. API 路由

路由處理器

方法用途
GET讀取資料
POST建立資料
PUT/PATCH更新資料
DELETE刪除資料

最佳實務

  • 使用 Zod 驗證輸入
  • 回傳適當的狀態碼
  • 妥善處理錯誤
  • 盡可能使用 Edge Runtime

5. 效能原則

圖片最佳化

  • 使用 next/image 元件
  • 為上方折頁設定優先級
  • 提供模糊佔位圖
  • 使用響應式尺寸

捆綁最佳化

  • 對重型元件使用動態導入
  • 基於路由的程式碼拆分(自動)
  • 使用捆綁分析器進行分析

6. 中繼資料

靜態 vs 動態

類型用途
靜態匯出固定中繼資料
generateMetadata每個路由動態產生

必要標籤

  • title(50-60 個字元)
  • description(150-160 個字元)
  • Open Graph 圖片
  • Canonical URL

7. 快取策略

快取層級

層級控制方式
請求fetch 選項
資料revalidate/tags
完整路由路由設定

重新驗證

方法用途
基於時間revalidate: 60
按需revalidatePath/Tag
無快取no-store

8. 伺服器動作

使用案例

  • 表單提交
  • 資料變更
  • 重新驗證觸發

最佳實務

  • 標記 'use server'
  • 驗證所有輸入
  • 回傳型別化的回應
  • 處理錯誤

9. 反模式

❌ 不要這樣做✅ 應該這樣做
到處使用 'use client'預設使用伺服器元件
在用戶端元件中擷取資料在伺服器元件中擷取資料
跳過載入狀態使用 loading.tsx
忽略錯誤邊界使用 error.tsx
大型客戶端捆綁動態導入

10. 專案結構

app/
├── (marketing)/     # 路由群組
│   └── page.tsx
├── (dashboard)/
│   ├── layout.tsx   # 儀表板佈局
│   └── page.tsx
├── api/
│   └── [resource]/
│       └── route.ts
└── components/
    └── ui/

請記住: 預設使用伺服器元件是有原因的。從那裡開始,只有在必要時才加入客戶端元件。

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

相關技能