关于 nextjs-mastery
面向 Next.js 开发者的实用参考技能,聚焦 App Router 应用构建,涵盖服务端数据处理、缓存、路由和常见实现误区。
主要功能
- 01App Router 结构组织
- 02服务端组件与数据获取
- 03ISR 与缓存重新验证
- 04Middleware 与 Server Actions
- 05实现检查清单和反模式
适用场景
- 01规划路由与布局结构
- 02选择服务端数据获取方式
- 03添加缓存和变更后重新验证
- 04检查 Next.js 实现
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ rohitg00/ awesome-claude-code-toolkit --skill nextjs-mastery安装后在 Claude Code 中输入/nextjs-mastery确认已加载。
详细介绍
Next.js 精通
App Router 结构
app/
layout.tsx # Root layout (wraps all pages)
page.tsx # Home route /
loading.tsx # Route-level Suspense fallback
error.tsx # Route-level error boundary
not-found.tsx # Custom 404
(marketing)/
about/page.tsx # /about (grouped without URL segment)
dashboard/
layout.tsx # Nested layout for /dashboard/*
page.tsx # /dashboard
@analytics/page.tsx # Parallel route slot
@activity/page.tsx # Parallel route slot
settings/
page.tsx # /dashboard/settings
api/
webhooks/route.ts # Route handler (POST /api/webhooks)
路由组 (name) 用于组织代码,但不会影响 URL。并行路由 @slot 可同时渲染多个页面。
服务端组件与数据获取
async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await db.product.findUnique({ where: { id } });
if (!product) notFound();
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={id} />
</Suspense>
</div>
);
}
async function Reviews({ productId }: { productId: string }) {
const reviews = await db.review.findMany({ where: { productId } });
return (
<ul>
{reviews.map(r => <li key={r.id}>{r.text} - {r.rating}/5</li>)}
</ul>
);
}
服务端组件是默认选项。它们在服务端运行,可直接访问数据库,且不会向客户端发送任何 JavaScript。
ISR 与缓存
export const revalidate = 3600;
async function BlogPage() {
const posts = await fetch("https://api.example.com/posts", {
next: { revalidate: 3600, tags: ["posts"] },
}).then(r => r.json());
return <PostList posts={posts} />;
}
import { revalidateTag, revalidatePath } from "next/cache";
export async function createPost(formData: FormData) {
"use server";
await db.post.create({ data: { title: formData.get("title") as string } });
revalidateTag("posts");
revalidatePath("/blog");
}
中间件
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("session")?.value;
if (request.nextUrl.pathname.startsWith("/dashboard") && !token) {
return NextResponse.redirect(new URL("/login", request.url));
}
const response = NextResponse.next();
response.headers.set("x-request-id", crypto.randomUUID());
return response;
}
export const config = {
matcher: ["/dashboard/:path*", "/api/:path*"],
};
中间件会在每个匹配的请求到达前于边缘运行。请保持中间件轻量。
服务端操作
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
const schema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
});
export async function updateProfile(prevState: any, formData: FormData) {
const parsed = schema.safeParse(Object.fromEntries(formData));
if (!parsed.success) {
return { errors: parsed.error.flatten().fieldErrors };
}
await db.user.update({
where: { email: parsed.data.email },
data: { name: parsed.data.name },
});
revalidatePath("/profile");
return { success: true };
}
反模式
- 在顶层布局或页面组件中添加
'use client' - 可以在服务端组件中完成时,仍在客户端获取数据
- 使用
useEffect获取数据,而不是使用服务端组件或use() - 未用
<Suspense>包裹耗时的异步组件 - 在中间件中放入繁重逻辑(它会在每个匹配的请求中运行)
- 忽略
loading.tsx和error.tsx约定
检查清单
- 默认使用服务端组件;仅在交互式叶子组件中使用
'use client' - 在服务端组件中获取数据,并正确设置缓存
- 使用
<Suspense>边界包裹相互独立的异步部分 - 为关键路由创建
loading.tsx和error.tsx - 中间件保持轻量,仅处理身份验证/重定向/标头
- 服务端操作在写入数据库前使用 Zod 验证输入
- 在数据变更后调用
revalidateTag或revalidatePath - 使用路由组和并行路由来组织复杂布局
评论
支持 Markdown