Skip to main content
AIPromptIndex
Cursor Coding intermediate

Next.js API Route Handler with Validation

Added Apr 2, 2026

Create a Next.js App Router API route handler for [ENDPOINT_PURPOSE] at the path [ROUTE_PATH]. The handler should support [HTTP_METHODS] methods. Use TypeScript and implement the following: 1) Request validation using Zod schemas for all inputs — path params, query params, and request body. Return descriptive 422 errors for validation failures with field-level messages. 2) Proper error handling with a try-catch wrapper that catches known error types (validation, auth, not-found, conflict) and returns appropriate HTTP status codes with consistent error response shapes. 3) Authentication check using [AUTH_METHOD] — return 401 for missing credentials and 403 for insufficient permissions. 4) Rate limiting headers in the response. 5) Type-safe response helpers that enforce the response schema at compile time. 6) Edge runtime compatibility if the handler does not need Node.js APIs. 7) Include JSDoc comments on the exported handler explaining the endpoint's purpose, parameters, and response codes. Generate the route handler file, the Zod schemas file, any shared types, and a sample test file using the Next.js test utilities. Follow Next.js 14+ App Router conventions with the route.ts file naming pattern.
0
Share
Try in Cursor

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
  }
}
```
nextjs api-routes typescript zod validation

Get the Best AI Prompts Weekly

Curated prompts, tips, and guides delivered to your inbox every week. Free.