C.W.K.
Stream
Lesson 01 of 09 · published

Route Handler

~20 min · route handler, API, REST

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

API route 진짜 필요할 때

Server Action 이 내부 mutation cover. Server Component 가 내부 data read cover. Route Handler 가 나머지 cover: webhook, third-party integration, public API — 외부에서 부를 수 있는 stable URL 노출하는 거.

모양

app/ 아래 어떤 folder 의 route.ts 가 HTTP method handler (GET, POST, PUT, DELETE 등) export. 각각 NextRequest 받고 NextResponse 반환.

Hard rule

route.ts 가진 folder 는 page.tsx 도 가질 수 없음. 다른 세계 (API vs UI) 서빙. Folder 별 하나만.

Code

GET + POST handler·ts
// app/api/posts/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  const params = request.nextUrl.searchParams;
  const page = Number(params.get('page') ?? 1);
  const posts = await db.post.findMany({ skip: (page - 1) * 10, take: 10 });
  return NextResponse.json(posts);
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  const post = await db.post.create({ data: body });
  return NextResponse.json(post, { status: 201 });
}
Param 가진 dynamic route handler·ts
// app/api/posts/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const post = await db.post.findUnique({ where: { id } });
  if (!post) return NextResponse.json({ error: 'Not found' }, { status: 404 });
  return NextResponse.json(post);
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  await db.post.delete({ where: { id } });
  return new NextResponse(null, { status: 204 });
}

External links

Exercise

app/api/stripe/route.ts 에 Stripe signature header 검증하고 database 에 write 하는 webhook endpoint. Stripe CLI 의 stripe listen 으로 test.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.