Use Cases

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 官方文档

#Claude Code #Next.js #全栈 #App Router #Server Components

让你的 Claude Code 工作流更上一层楼

50 个经过实战检验的提示词模板,现在就能复制粘贴到 Claude Code 中使用。

免费

免费 PDF:5 分钟看懂 Claude Code 速查表

关键命令、快捷键与提示词示例,整理在一页可打印的 A4 纸上。

下载 PDF
M

本文作者

Masa

深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。