Accelerating Next.js Full-Stack Development with Claude Code
Learn about accelerating next.js full-stack development using Claude Code. Practical tips and code examples included.
Next.js × Claude Codeでフルスタック開発
Next.jsのApp Routerは、フロントエンドとバックエンドを統合的に開発できるフレームワークです。Claude Codeと組み合わせることで、ページ、APIルート、データベース連携までを一気に構築できます。
プロジェクトの初期セットアップ
> Next.js 14 + TypeScript + Tailwind CSS + Prismaの
> プロジェクトを作成して。App Routerを使用。
> 以下の構成で:
> - src/app: ページ・レイアウト
> - src/components: 共通コンポーネント
> - src/lib: ユーティリティ・DB接続
> - prisma: スキーマ・マイグレーション
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) は認証必須。
DB連携の詳細はDBマイグレーション自動化を、Reactコンポーネントの設計はReact開発を爆速にする方法を参照してください。日々の開発効率を上げるコツは生産性を3倍にする10のTipsもあわせてご覧ください。
Zusammenfassung
Claude CodeとNext.jsの組み合わせは、フルスタック開発を劇的に加速します。Server Components、Server Actions、API Routeを一貫して生成できるため、フロントエンドからバックエンドまでシームレスに開発を進められます。
Next.jsの詳細はNext.js公式ドキュメント、Claude CodeについてはAnthropic公式ドキュメントを参照してください。
Related Posts
So beschleunigen Sie Ihre Nebenprojekte mit Claude Code [Mit Beispielen]
Erfahren Sie, wie Sie persönliche Entwicklungsprojekte mit Claude Code drastisch beschleunigen. Inklusive realer Beispiele und eines praktischen Workflows von der Idee bis zum Deployment.
So automatisieren Sie Refactoring mit Claude Code
Erfahren Sie, wie Sie Code-Refactoring mit Claude Code effizient automatisieren. Inklusive praktischer Prompts und konkreter Refactoring-Muster für reale Projekte.
Vollständiger CORS-Konfigurationsleitfaden mit Claude Code
Erfahren Sie alles über die CORS-Konfiguration mit Claude Code. Mit praktischen Tipps und Codebeispielen.