→ cards/06-api-route

Chapter

06 · API Route (app/(api)/<entity>/route.ts)

External contract only: adapt HTTP → entity actions; never used by internal UI.

Mental Model

  • API routes are borders for external consumers (integrations, scripts, webhooks).
  • They adapt HTTP to entity actions; they do not own data or rules.

File Classification

Layer: External integration
Runtime: Server
Consumers: Non-UI clients
Prisma: ❌ Never
Entity Actions: ✅ Yes
UI/Internal use: ❌ Never

Canonical Examples

import { getProjects } from "@/app/(index)/projects/actions/getProjects";

export async function GET(req: Request) {
assertAuthorized(req);
const projects = await getProjects();
return Response.json({ projects });
}

import { createProject } from "@/app/(index)/projects/actions/createProject";
import { revalidatePath } from "next/cache";

export async function POST(req: Request) {
assertAuthorized(req);
const body = await req.json();
await createProject(body);
revalidatePath("/projects");
return new Response(null, { status: 201 });
}

Never Do (and where it belongs)

  • Serve internal UI → use server pages/actions instead.
  • Prisma directly → keep in entity actions.
  • Business rules duplication → centralize in entity actions.