| name | create-api-endpoints |
| description | Use when creating new Next.js route handlers using the custom helper wrapper. |
Create API Endpoints Playbook
To build route handlers quickly and securely without writing boilerplate validation or session-guard blocks, use the custom createApiRoute helper located in src/lib/api.ts.
Step-by-Step Flow:
-
Import the Helper & Zod:
import { createApiRoute } from "@/lib/api";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
-
Define the Route Handler:
Wrap your execution inside createApiRoute. You can specify guards and parse schemas:
export const POST = createApiRoute({
requireAuth: true,
requireAdmin: false,
schema: z.object({
amount: z.number().positive(),
description: z.string().min(3)
}),
handler: async (req, { session, body, params }) => {
const newRecord = await prisma.item.create({
data: {
title: body.description,
category: "LOGS",
ownerId: session.user.id
}
});
return newRecord;
}
});
-
Exception Handling:
Do not wrap the inner handler in extensive try/catch blocks unless you want custom responses. The wrapper intercepts database errors and returns a formatted 500 Internal Server Error automatically.