Claude Code 加速 Next.js 全栈开发实战
基于 App Router 的 Next.js 14 项目:用 Claude Code 同时生成页面、Server Actions、API Route 与 Prisma 数据层。
Next.js × Claude Code 全栈开发
Next.js 的 App Router 是一套前后端一体的开发框架。结合 Claude Code,页面、API Route、数据库联动可以一口气全部搭起来。
项目初始化
> 帮我初始化一个 Next.js 14 + TypeScript + Tailwind CSS + Prisma 的项目。
> 使用 App Router。
> 目录结构如下:
> - src/app: 页面和布局
> - src/components: 公共组件
> - src/lib: 工具函数、数据库连接
> - prisma: Schema 和迁移
Server Components 的用法
用 Server Components 处理数据获取的模式:
> 用 Server Component 写一个博客文章列表页面。
> 从 Prisma 取数据,支持分页。
// src/app/posts/page.tsx
import { prisma } from "@/lib/prisma";
import { PostCard } from "@/components/PostCard";
import { Pagination } from "@/components/Pagination";
interface Props {
searchParams: Promise<{ page?: string }>;
}
export default async function PostsPage({ searchParams }: Props) {
const { page: pageParam } = await searchParams;
const page = Number(pageParam) || 1;
const perPage = 12;
const [posts, total] = await Promise.all([
prisma.post.findMany({
take: perPage,
skip: (page - 1) * perPage,
orderBy: { createdAt: "desc" },
include: { author: { select: { name: true, avatar: true } } },
}),
prisma.post.count(),
]);
return (
<main className="container mx-auto px-4 py-8">
<h1 className="mb-8 text-3xl font-bold">文章列表</h1>
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
<Pagination
currentPage={page}
totalPages={Math.ceil(total / perPage)}
basePath="/posts"
/>
</main>
);
}
export const metadata = {
title: "文章列表",
description: "显示所有文章",
};
Server Actions 的用法
表单处理用 Server Actions 实现:
> 用 Server Actions 实现一个文章创建表单。
> 校验用 zod,错误处理也带上。
// src/app/posts/new/actions.ts
"use server";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { z } from "zod";
const CreatePostSchema = z.object({
title: z.string().min(1, "标题为必填").max(200),
content: z.string().min(10, "正文至少需要 10 个字符"),
published: z.boolean().default(false),
});
export type FormState = {
errors?: Record<string, string[]>;
message?: string;
};
export async function createPost(
prevState: FormState,
formData: FormData
): Promise<FormState> {
const parsed = CreatePostSchema.safeParse({
title: formData.get("title"),
content: formData.get("content"),
published: formData.get("published") === "on",
});
if (!parsed.success) {
return { errors: parsed.error.flatten().fieldErrors };
}
await prisma.post.create({
data: { ...parsed.data, authorId: "current-user-id" },
});
redirect("/posts");
}
创建 API Route
对外集成用的 API Route 也能一起生成。
> 创建 /api/posts 的 Route Handler。
> GET(列表、搜索、分页)和 POST(创建)。
> 包含鉴权检查。
// src/app/api/posts/route.ts
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const page = Number(searchParams.get("page")) || 1;
const q = searchParams.get("q") || "";
const limit = 20;
const where = q
? { title: { contains: q, mode: "insensitive" as const } }
: {};
const [posts, total] = await Promise.all([
prisma.post.findMany({
where,
take: limit,
skip: (page - 1) * limit,
orderBy: { createdAt: "desc" },
}),
prisma.post.count({ where }),
]);
return NextResponse.json({
data: posts,
meta: { page, limit, total },
});
}
export async function POST(request: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await request.json();
const post = await prisma.post.create({
data: { ...body, authorId: session.user.id },
});
return NextResponse.json({ data: post }, { status: 201 });
}
中间件配置
用中间件来守卫受认证保护的路由:
> 用中间件保护需要登录的路由。
> /dashboard, /posts/new, /api/posts(POST) 必须登录。
数据库相关的细节请参考 数据库迁移自动化,React 组件设计看 React 开发加速指南。日常开发效率提升技巧请参考 生产力提升的 10 条 Tips。
总结
Claude Code 与 Next.js 的组合能让全栈开发效率大幅提升。Server Components、Server Actions、API Route 都可以一气生成,让前后端无缝衔接。
更多信息请参阅 Next.js 官方文档 和 Anthropic 官方文档。
免费 PDF:5 分钟看懂 Claude Code 速查表
只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。
我们会严格保护你的个人信息,绝不发送垃圾邮件。
把 Claude Code 变成真正能带来结果的工作流
先领取中文说明的免费 PDF,再进入英文商品页选择合适的教材。如果你需要团队落地、流程设计或内容变现支持,也可以直接咨询。
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
每天发布多语言 Claude Code 文章前,要先检查的 7 件事
一份实用清单,帮助你每天发布多语言 Claude Code 文章时避免漏语言、CTA 错位和线上内容未更新。
Codex Automations 是什么?让 AI 在你睡觉时完成内容运营
用 Codex Automations 自动查看流量、选择主题、写文章、改善转化路径并部署网站的实用指南。
Claude Code × GCP Cloud Functions 完全指南 | 极速开发无服务器函数
用 Claude Code 高效开发 GCP Cloud Functions。从 HTTP/Pub/Sub/Firestore 触发器实现到本地测试、部署自动化,基于 Masa 的实战经验,附完整可运行代码示例。