What this prompt does
This prompt designs a clean API-layer architecture for a Next.js App Router app so every route shares the same auth, validation, and error shape instead of each handler improvising. It produces route handler patterns, a composable middleware chain, Zod request validation, a consistent error-response format with proper status codes, rate limiting, CORS configuration, API-key auth, request logging, and a type-safe client for the frontend — plus the folder structure under app/api/.
The variables define the surface and its protections. [nextjs_version] sets the target, [api_endpoints] lists the routes to design handlers for, and [middleware_stack] names the layers (auth, rate-limit, validate, log) that compose around each handler. [rate_limit_strategy] picks the throttling approach (sliding window with Redis) and [allowed_origins] configures CORS. The core idea is a composable middleware chain plus Zod schemas enforcing consistency, and settling on one error-response format early so the frontend client is far simpler to build against. A utility for composing middleware keeps the pattern reusable across every endpoint.
When to use it
- Standardizing a Next.js API so every route handles auth and errors identically
- Introducing a composable middleware chain instead of repeating logic per handler
- Enforcing request validation with shared Zod schemas
- Settling on one error-response shape before building the frontend client
- Adding rate limiting and CORS in a structured, reusable way
- Generating a type-safe API client so the frontend can't call routes wrong
Example output
You get route handler patterns for your [api_endpoints], a middleware-composition utility implementing the [middleware_stack] in order, Zod schemas validating requests, a single error-response format with correct HTTP status codes, rate limiting via your [rate_limit_strategy], CORS rules for [allowed_origins], API-key auth middleware, request logging, and a type-safe client for the frontend. The folder structure under app/api/ is laid out explicitly. The result is an enforceable convention every new endpoint can follow rather than a pile of one-off handlers.
Pro tips
- Order
[middleware_stack]deliberately (auth, rate-limit, validate, log); the sequence determines what runs before what and changes behavior meaningfully - Define one error-response shape and stick to it — that single format is what makes the type-safe client simple to build and consume
- Keep one Zod schema per endpoint and reuse it in the client so request types can't drift from the server
- Match
[rate_limit_strategy]to your infra; sliding window with Redis is robust, but needs Redis available in every environment - Scope
[allowed_origins]tightly to the domains that need access rather than a permissive wildcard - Use the middleware-composition utility for every route so the consistency is enforced structurally, not by convention alone