Next.js Route Handlers & API Patterns
N نکست.جی‌اس

Next.js Route Handlers & API Patterns

Build REST endpoints in the App Router with route.ts, HTTP methods, and streaming responses.

BugCast Admin··۵ دقیقه مطالعه

Route Handlers replace API routes in the App Router. They export functions named after HTTP verbs and return Web Standard Response objects.

Common Interview Questions

Q: Basic route handler structure?

Answer: Colocate handlers in route.ts files. Export GET, POST, PUT, PATCH, DELETE as needed.


// app/api/users/route.ts
export async function GET() {
  const users = await db.user.findMany();
  return Response.json(users);
}

export async function POST(request: Request) {
  const body = await request.json();
  const user = await db.user.create({ data: body });
  return Response.json(user, { status: 201 });
}

Q: Route handlers vs Server Actions?

Answer: Route handlers are HTTP endpoints for any client (mobile, webhooks). Server Actions are RPC-style mutations from React components with built-in progressive enhancement.

Q: Dynamic route segments in APIs?

Answer: In Next.js 15+, params is a Promise and must be awaited in async handlers.


// app/api/posts/[id]/route.ts
export async function GET(_req, { params }) {
  const { id } = await params;
  return Response.json(await getPost(id));
}

Q: CORS in route handlers?

Answer: Set Access-Control-* headers on Response or use middleware. For public APIs, handle OPTIONS preflight explicitly.

Key Points for Interviews

  • route.ts cannot export page default alongside handlers

  • Use Web Response/Request APIs

  • Validate input and authenticate every mutation

  • Edge or Node runtime via export const runtime

  • Coexist with legacy pages/api during migration

#route-handlers#api#interview

مطالب مرتبط