---
name: nextjs-api-route-optimizer
description: "Writes a Next.js API route built for speed around your data layer: cache headers or in-memory caching, streaming, batching, or minimal latency, with the trade-offs commented inline. Use when an API route that hits Prisma or Mongo or Supabase needs to be built for speed with caching, streaming, batching, or lowest latency as the goal. Do not use for a basic CRUD route with no performance target, or finding a bug in a slow route. Related topics: coding, next.js."
---

# Next.js API Route Optimizer

Writes a Next.js API route built for speed around your data layer: cache headers or in-memory caching, streaming, batching, or minimal latency, with the trade-offs commented inline.

## When to use

Use this skill when an API route that hits Prisma or Mongo or Supabase needs to be built for speed with caching, streaming, batching, or lowest latency as the goal. Do not use it for a basic CRUD route with no performance target, or finding a bug in a slow route.

## Workflow

1. Ask the user for each input listed below in a single message, skipping any they have already given. Where options are listed, offer them, but accept other answers too.
2. Reuse one database client across invocations and select only the fields the response needs, so connection setup and over-fetching are gone.
3. Implement the chosen focus: cache headers plus a TTL map, chunked streaming, batched queries in request order, or latency short-circuits.
4. Wrap the handler with the selected middleware in the order auth, rate limit, CORS, validation.
5. Comment every section with its purpose and the trade-off it accepts, then output the full JavaScript route.

## Inputs

- **Endpoint path** (free text, e.g. "/api/example")
- **HTTP method** (choose one: GET, POST, PUT, DELETE, PATCH)
- **Request payload schema** (longer free text)
- **Response structure** (longer free text)
- **Database interaction** (choose any: Prisma, MongoDB, Supabase, None)
- **Middleware needed** (choose any: Auth, Rate limiting, Validation, CORS, None)
- **Performance focus** (choose one: Caching, Streaming, Batching, Minimal latency)

## Output

One JavaScript code block with the full route: client setup, middleware wrappers, the handler implementing the chosen performance focus, and inline comments on each section's trade-off.

## Prompt template

Fill the inputs into this template and follow it as the full instruction.

### Next.js API Route Optimizer

Create a performance-focused Next.js API route.

- Endpoint path: {{Endpoint path}}
- HTTP method: {{HTTP method}}
- Request payload schema: {{Request payload schema}}
- Response structure: {{Response structure}}
- Database interaction: {{Database interaction}}
- Middleware needed: {{Middleware needed}}
- Performance focus: {{Performance focus}}

Decide where the time goes before writing code: for a database-backed route it is almost always the query count and the connection setup, so reuse a single client instance across invocations (a module-level Prisma client, a cached Mongo connection, a Supabase client created once) and select only the fields the response needs. Then apply the chosen focus. Caching: set Cache-Control with s-maxage and stale-while-revalidate for GET responses that tolerate staleness, and add an in-memory map with TTL for hot keys, noting it is per instance. Streaming: write the response in chunks as rows arrive and flush, with the content type set up front. Batching: accept an array of ids or operations, run them in one query or a single transaction, and return results in request order. Minimal latency: short-circuit on validation failures, avoid awaiting anything not needed for the response, and defer logging to after the response is sent. Add the selected middleware as light wrappers in the order auth, rate limit, CORS, validation. Comment each section with what it does and the trade-off it accepts. Return the complete route in JavaScript as one code block with inline comments.

## Pitfalls

- Creating a new database client on every request, which costs more than any caching trick saves.
- Caching a response that varies by user without the user in the cache key, which leaks data across sessions.
- Setting headers after the first streamed chunk, which throws because the headers are already sent.
- Batching into one transaction that fails entirely on the first bad item without saying which item failed.
