API ROUTE
api-route.ts
Validation, auth, service call, consistent response format.
StarkWHAT THIS PATTERN TEACHES
How to structure API routes that validate input with Zod, check auth, delegate to services, and return typed responses.
WHEN TO USE THIS
Every API endpoint. This is the entry point pattern for all server-side request handling.
AT A GLANCE
export async function POST(req: NextRequest) {
const body = schema.parse(await req.json())
const result = await service.create(body)
return NextResponse.json(result)
}FRAMEWORK IMPLEMENTATIONS
TypeScript
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { projectService } from "@/services/project";
import { getSession } from "@/lib/auth";
import { ApiError } from "@/lib/errors";
const CreateProjectSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
workspaceId: z.string().uuid(),
});
export async function POST(req: NextRequest) {
try {
const session = await getSession(req);
if (!session) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 }
);