agentleFS
bkjain655bkjain655/agent-skills/skills/nextjs-api-routes/SKILL.md

nextjs-api-routes

Skill0 starsChanged 3 months agoMITView on GitHub

Next.js Route Handlers: POST/GET APIs, Zod validation, typed errors, rate limiting, and env-gated features. Use when creating API routes, form backends, webhooks, or securing public endpoints.

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Never leak stack traces to client in production.

    line 89

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Next.js API Routes

Route handler basics

// app/api/feedback/route.ts
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  return NextResponse.json({ ok: true });
}

export const runtime = "nodejs"; // when Playwright/sharp/fs needed

Zod validation

const schema = z.object({
  email: z.string().email(),
  message: z.string().min(1).max(5000),
});

export async function POST(req: Request) {
  const body = await req.json().catch(() => null);
  const parsed = schema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  }
  // use parsed.data
}

Colocate schemas in lib/schemas/*.schema.ts + unit tests.

Reusable POST factory (optional)

export function createPostRoute<T>(opts: {
  schema: z.ZodType<T>;
  handler: (data: T, req: Request) => Promise<void>;
  rateLimitKey?: string;
}) {
  return async function POST(req: Request) {
    if (opts.rateLimitKey && !(await checkRateLimit(req, opts.rateLimitKey))) {
      return NextResponse.json({ error: "Too many requests" }, { status: 429 });
    }
    const parsed = opts.schema.safeParse(await req.json());
    if (!parsed.success) return NextResponse.json({ error: "Invalid input" }, { status: 400 });
    try {
      await opts.handler(parsed.data, req);
      return NextResponse.json({ ok: true });
    } catch (e) {
      return NextResponse.json({ error: "Server error" }, { status: 500 });
    }
  };
}

Rate limiting

In-memory for dev; Upstash Redis for production:

export async function checkRateLimit(req: Request, bucket: string, limit = 10, windowSec = 60) {
  const ip = req.headers.get("x-forwarded-for") ?? "anonymous";
  // increment counter for `${bucket}:${ip}` in Redis or Map
}

Return 429 with Retry-After when exceeded.

Feature flags (503 when disabled)

if (!isEmailConfigured()) {
  return NextResponse.json({ error: "Feature not configured" }, { status: 503 });
}

Never leak stack traces to client in production.

Security checklist

- [ ] Validate all input with Zod
- [ ] Rate-limit public POST routes
- [ ] Secrets only in server env (no NEXT_PUBLIC_)
- [ ] Escape user content in HTML emails
- [ ] CSRF: same-site cookies or nonce for sensitive actions
- [ ] Cap payload/attachment size

Anti-patterns

  • Trusting client-only validation
  • Returning 200 with { error: "..." } instead of proper status codes
  • Constructing Resend/DB clients at module top level without env check
  • Logging PII in error handlers

Pair with: resend-email-nextjs, vitest-unit-testing.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.