Next.js App Router API Handler

fullstack
TypeScript
scaffolding
corporate_pm
Remix

Type-safe Next.js API route with validation, error handling, and proper HTTP status codes.

12/8/2025

Prompt

Next.js App Router API Handler

Create a type-safe Next.js 14 App Router API route handler at app/api/[path]/route.ts for [HTTP Method] requests.

Requirements

1. Request Validation

  • Use Zod for schema validation
  • Detailed validation rules
  • Type-safe input parsing

2. Database Queries

  • Use type-safe ORM (Prisma/Drizzle)
  • Proper error handling for queries

3. Error Handling

  • Comprehensive try-catch blocks
  • Return appropriate HTTP status codes:
    • 200 - Success
    • 201 - Created
    • 400 - Bad Request
    • 401 - Unauthorized
    • 404 - Not Found
    • 500 - Internal Server Error

4. CORS Headers

  • Add if needed for cross-origin requests

5. Logging

  • Log incoming requests
  • Log errors and important operations

6. Response Format

  • Return JSON with NextResponse.json()
  • Consistent response structure

7. Documentation

  • Add JSDoc comments
  • Explain endpoint purpose and parameters

Structure

export async function [METHOD](request: Request) {
  // implementation
}

Make it production-ready with all best practices.

Tags

nextjs
api
app-router
zod

Tested Models

claude-3-sonnet
gpt-4

Comments (0)

Sign in to leave a comment

Sign In