Communitygithub.com

Next.js 最佳实践

涵盖 Next.js App Router 的核心原则:服务端组件、数据获取与路由模式。

Next.js 最佳实践 是什么?

该技能全面梳理了 Next.js App Router 开发中的关键实践与决策原则。它通过清晰的对比表格和决策树,指导开发者何时使用服务端组件(Server Components)或客户端组件(Client Components),并深入讲解数据获取策略(如静态生成、ISR 和动态获取)以及文件路由约定(如 page.tsx、layout.tsx 等)。技能还涵盖了路由组织技巧(并行路由、拦截路由)、API 路由处理、性能优化(next/image、动态导入)、元数据管理、多层缓存策略及服务端操作(Server Actions)的最佳实践。同时明确指出常见反模式及其解决方案,并给出了推荐的项目结构,帮助开发者构建高效、可维护的 Next.js 应用。该技能适用于所有使用 App Router 的 Next.js 项目,无论是新建还是迁移。

兼容平台~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. 服务端组件 vs 客户端组件

决策树

需要...?
│
├── useState、useEffect、事件处理程序
│   └── 客户端组件 ('use client')
│
├── 直接数据获取,无交互
│   └── 服务端组件(默认)
│
└── 两者都需要?
    └── 拆分:服务端父组件 + 客户端子组件

默认选择

类型用途
服务端数据获取、布局、静态内容
客户端表单、按钮、交互式 UI

2. 数据获取模式

获取策略

模式用途
默认静态(构建时缓存)
RevalidateISR(基于时间的刷新)
No-store动态(每次请求)

数据流

来源模式
数据库服务端组件 fetch
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 运行时

5. 性能原则

图片优化

  • 使用 next/image 组件
  • 为首屏内容设置 priority
  • 提供模糊占位符
  • 使用响应式尺寸

打包优化

  • 对重量级组件使用动态导入
  • 基于路由的代码分割(自动)
  • 使用打包分析器进行分析

6. 元数据

静态 vs 动态

类型用途
静态导出固定元数据
generateMetadata按路由动态生成

必备标签

  • title(50-60 字符)
  • description(150-160 字符)
  • Open Graph 图片
  • Canonical URL

7. 缓存策略

缓存分层

层控制
请求fetch 选项
数据revalidate/tags
完整路由路由配置

重新验证

方法用途
基于时间revalidate: 60
按需revalidatePath/Tag
无缓存no-store

8. 服务端操作 (Server Actions)

使用场景

  • 表单提交
  • 数据变更
  • 触发重新验证

最佳实践

  • 使用 'use server' 标记
  • 验证所有输入
  • 返回带类型的响应
  • 处理错误

9. 反模式

❌ 不要✅ 应该
到处使用 'use client'默认使用服务端组件
在客户端组件中 fetch在服务端组件中 fetch
跳过加载状态使用 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

相关技能