E

Efficient Nextjs Handler

All-in-one command covering comprehensive, next, performance, audit. Includes structured workflows, validation checks, and reusable patterns for nextjs vercel.

CommandClipticsnextjs vercelv1.0.0MIT
0 views0 copies

Efficient Next.js Handler

Generate optimized Next.js API route handlers with proper request parsing, response formatting, error handling, input validation, and TypeScript types for both App Router and Pages Router.

When to Use This Command

Run this command when you need to create a new Next.js API route handler with production-ready patterns.

  • You are creating a new API endpoint and want a well-structured handler template
  • You need proper TypeScript types for request and response objects
  • You want consistent error handling, validation, and response formatting across all API routes
  • You need to support multiple HTTP methods (GET, POST, PUT, DELETE) in a single route

Use it also when:

  • You want to generate both App Router (route.ts) and Pages Router (handler.ts) versions
  • You need middleware-like functionality (auth, logging) built into the handler

Quick Start

# .claude/commands/efficient-nextjs-handler.md name: efficient-nextjs-handler description: Generate optimized Next.js API route handlers arguments: path: API route path (e.g., /api/users)
# Generate a handler for a new API route claude efficient-nextjs-handler "/api/users"
Expected output:
Generated API handler: /api/users
  File: app/api/users/route.ts
  Methods: GET (list), POST (create)

  Features:
    - Request body validation (Zod)
    - Error handling with status codes
    - TypeScript request/response types
    - Pagination support for GET
    - Created response for POST

Core Concepts

ConceptDescription
Route HandlerApp Router API function exported as GET, POST, PUT, DELETE
API RoutePages Router handler using NextApiRequest / NextApiResponse
ValidationRequest body and query parameter validation using Zod or similar
Error BoundaryTry-catch wrapper with proper HTTP status codes
Response HelperConsistent JSON response formatting with type safety
Handler Architecture:
  Request ──> Parse Input ──> Validate ──> Business Logic ──> Response
                                │                               │
                                v                               v
                          400 Bad Request              200/201 Success
                                                      500 Server Error

Configuration

ParameterDefaultDescription
pathrequiredAPI route path (e.g., /api/users)
routerauto-detectapp (App Router) or pages (Pages Router)
methodsGET,POSTHTTP methods to generate handlers for
validationzodValidation library: zod, yup, or manual
authfalseInclude authentication check in handler

Best Practices

  1. Export named functions for App Router -- Use export async function GET() instead of a default export. Each HTTP method gets its own exported function.

  2. Validate all inputs at the handler boundary -- Parse and validate request body, query params, and route params before they reach business logic.

  3. Return consistent error shapes -- Use a standard error response format like { error: string, details?: object } across all handlers for client-side error handling.

  4. Separate business logic from handler logic -- Keep the route handler thin. Move domain logic to service functions that can be tested independently.

  5. Use NextResponse for App Router -- Return NextResponse.json() instead of res.json() in App Router handlers for proper typing and edge runtime compatibility.

Common Issues

  1. Handler not matching requests -- In App Router, the file must be named route.ts (not handler.ts or index.ts) and placed in the correct app/api/ subdirectory.

  2. Body parsing fails for GET requests -- GET requests do not have a body. Use request.nextUrl.searchParams for query parameters instead of request.json().

  3. CORS errors in development -- API routes do not include CORS headers by default. Add Access-Control-Allow-Origin headers or configure middleware for cross-origin requests.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates