Next.js API Route Handler with Validation
Added Apr 2, 2026
About This Prompt
This prompt generates Next.js API route handlers that handle the boring but critical parts of API development — validation, error handling, authentication, and type safety — so you can focus on business logic. The Zod schema integration catches malformed requests before they reach your handler, while the typed response helpers prevent you from accidentally returning the wrong shape. The consistent error response format means your frontend team always knows what to expect when something fails. The included test file gives you a starting point for route testing, which is often skipped because the setup is tedious. Ideal for teams building Next.js applications who want their API routes to be as robust as a dedicated backend service.
Variables to Customize
[ENDPOINT_PURPOSE]
What the API endpoint does
Example: managing user workspace invitations — creating, listing, accepting, and revoking invites
[ROUTE_PATH]
The API route path
Example: /api/workspaces/[workspaceId]/invitations
[HTTP_METHODS]
Which HTTP methods to implement
Example: GET (list invitations), POST (create invitation), PATCH (accept/decline)
[AUTH_METHOD]
How authentication is handled
Example: NextAuth.js session with role-based access control (owner, admin, member roles)
Tips for Best Results
- Include your existing error handling pattern or middleware if you have one so Cursor stays consistent
- Specify your database ORM (Prisma, Drizzle, etc.) so the handler uses the right query patterns
- Ask Cursor to generate the corresponding frontend fetch hooks alongside the route handler
Example Output
```typescript
// app/api/workspaces/[workspaceId]/invitations/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
const CreateInvitationSchema = z.object({
email: z.string().email('Invalid email address'),
role: z.enum(['admin', 'member'], {
errorMap: () => ({ message: 'Role must be admin or member' }),
}),
});
const ParamsSchema = z.object({
workspaceId: z.string().uuid('Invalid workspace ID'),
});
/**
* POST /api/workspaces/[workspaceId]/invitations
* Creates a new workspace invitation and sends an email.
* Requires: owner or admin role in the workspace.
* Returns: 201 with invitation object, or 409 if already invited.
*/
export async function POST(
request: NextRequest,
{ params }: { params: { workspaceId: string } }
) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
);
}
// ... validation and business logic
} catch (error) {
// ... error handling
}
}
```