AGENT SKILL

nextjs-check-route-types

Type-system hygiene for Next.js App Router routes -- `any`-typed params, missing route handler signatures, generated-types staleness from `next dev` and `next build` typecheck gaps. Triggers on Next.js route handler authoring (`app/**/route.ts`, `app/**/page.tsx` typed-segments). Not agent-specific security; complementary to runtime hardening.

License 许可
MIT
所属仓库
MILTONADINA/DevOPs
最近更新
2026-11-14
Stars
★ 0
Forks
0

01 前言 Front Matter

name
nextjs-check-route-types
description
Type-system hygiene for Next.js App Router routes -- `any`-typed params, missing route handler signatures, generated-types staleness from `next dev` and `next build` typecheck gaps. Triggers on Next.js route handler authoring (`app/**/route.ts`, `app/**/page.tsx` typed-segments). Not agent-specific security; complementary to runtime hardening.

02 资源文件 1

03 SKILL.md 正文

Next.js Route Type Checking

This skill addresses type-system correctness, not agent-specific security. The patterns here close compile-time blind spots that allow runtime bugs and complicate review; they are NOT the load-bearing defense against any OWASP ASI / AST threat. The runtime hardening of route handlers is the responsibility of skills/stack-specific/nextjs/server-action-safety/SKILL.md and the universal security/prompt-injection-defense skill.

Tradeoff: Stricter route typing catches a class of integration bugs at build time rather than at request time. Cost: per-PR friction when Next.js's generated types (.next/types/...) lag behind route file changes during local development.


Why this matters

Next.js App Router generates route types from the file system shape during next dev and next build (and next typegen on 15.5+): app/posts/[slug]/route.ts produces a typed { params: Promise<{ slug: string }> } context argument. When those generated types are stale (e.g., a new dynamic segment added but next dev hasn't re-generated), the handler signature reverts to a permissive default and runtime arguments flow through unchecked. Reviewers see "the types pass" without realizing the types are vacuous.

This is a footgun across the entire surface area:

  • app/api/**/route.ts handlers with implicit-any parameters.
  • app/[slug]/page.tsx route segments with un-narrowed param types.
  • searchParams accessed without runtime validation.
  • Proxy (proxy.ts; middleware.ts before Next.js 16) reading headers without typing them.

None of these are security failures on their own. They're conditions under which a separate runtime-validation gap (the actual security control) hides because the type checker isn't complaining.


Pattern 1 -- Always type route handler signatures explicitly

The compile-time signature for an App Router handler:

// app/api/posts/[slug]/route.ts
import { NextRequest, NextResponse } from 'next/server';

type RouteContext = {
  params: Promise<{ slug: string }>;
};

export async function GET(
  request: NextRequest,
  context: RouteContext,
): Promise<NextResponse> {
  const { slug } = await context.params;
  // ... handler body ...
  return NextResponse.json({ slug });
}

Explicit NextRequest (NOT bare Request) gives access to Next.js- specific fields (request.nextUrl, request.cookies). Explicit RouteContext ties the handler's expected dynamic segments to the file path; a renamed segment that doesn't match slug is a compile error.

Note Next.js 15+ awaits params as a Promise. Older code with sync params won't compile against newer Next.js without migration.


Pattern 2 -- Validate searchParams at the route boundary

import { z } from 'zod';

const SearchSchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  perPage: z.coerce.number().int().min(1).max(100).default(20),
  q: z.string().max(200).optional(),
});

export async function GET(request: NextRequest) {
  const parsed = SearchSchema.safeParse(
    Object.fromEntries(request.nextUrl.searchParams),
  );
  if (!parsed.success) {
    return NextResponse.json({ error: 'invalid query' }, { status: 400 });
  }
  const { page, perPage, q } = parsed.data;
  // ... use typed values, NOT raw searchParams ...
}

searchParams is URLSearchParams. Its .get() returns string | null; there's no compile-time guarantee that the query string contains what the handler assumes. Runtime validation closes the gap.


Pattern 3 -- Regenerate types on dynamic-segment renames

When you rename app/posts/[slug]/route.ts to app/posts/[postId]/route.ts, the next next build (or next dev HMR refresh) regenerates the RouteContext types with the new param name. UNTIL that happens, the handler still compiles against the old generated types.

Discipline: after any file-system rename inside app/, run next typegen && tsc --noEmit (Next.js 15.5+; on older versions, next build) before committing. Run the same pair in CI: plain tsc --noEmit does not generate route types, so on its own it checks against stale or missing .next/types and can pass.


Anti-patterns

Anti-pattern 1 -- any-typed handler params

// WRONG
export async function GET(request, context: any) {
  const slug = context.params.slug;  // no type narrowing
  // ...
}

any defeats the entire type system. A renamed segment, a missing param, a wrong-shaped context object all flow through silently. Always type both request and context explicitly.

Anti-pattern 2 -- Trusting raw searchParams.get() without validation

// WRONG
export async function GET(request: NextRequest) {
  const page = request.nextUrl.searchParams.get('page');  // string | null
  const offset = parseInt(page) * 20;  // NaN if page missing
  // ...
}

parseInt(null) is NaN. The handler computes a NaN offset and silently returns whatever the DB does with that. Runtime validation (Pattern 2) is the fix.

Anti-pattern 3 -- Generated-types staleness ignored across deploys

// WRONG: file renamed from [slug] to [postId] but the handler still reads
// context.params.slug because the generated types haven't refreshed.
type RouteContext = { params: Promise<{ slug: string }> };  // STALE

The handler compiles locally because the old .next/types/* cache still defines slug. On a fresh CI build (clean .next/), the types regenerate to { postId: string } and the handler fails compile. Or worse: the handler ships, runtime accesses params.slug which is now undefined, and silent NaN / null-deref bugs follow.


ASI/AST mapping

No canonical ASI/AST applies -- type-system hygiene is general software-correctness discipline, not an agent-specific threat surface. The runtime-validation gaps these patterns close are protected at a different layer (the runtime input-validation patterns in stack-specific/nextjs/server-action-safety and the universal security/prompt-injection-defense); this skill is the compile-time counterpart that prevents the runtime gaps from going unnoticed in review.

Skills that DO cover the runtime side of route safety:

  • skills/stack-specific/nextjs/server-action-safety/SKILL.md -- ASI02 + ASI03 for Server Actions
  • skills/universal/security/prompt-injection-defense/SKILL.md -- ASI01 + ASI04 for content entering the handler

When this skill is working

  • next typegen && tsc --noEmit passes cleanly in CI on every PR, no any-typed route handlers in the diff.
  • Route-segment renames are paired with type-regeneration in the same commit.
  • searchParams access goes through a Zod (or equivalent) parser at the handler boundary.

See also

04 同仓库更多 Skills

MILTONADINA
MILTONADINA/DevOPs

karpathy-guidelines

Behavioral guidelines that reduce common LLM coding mistakes. Apply whenever writing, modifying, or reviewing code. Don't assume requirements, don't overcomplicate, don't refactor unrelated code, and define success criteria before implementing. Use this skill on every non-trivial coding task to avoid bloat, silent assumptions, and completion-bias.

★ 0
MILTONADINA
MILTONADINA/DevOPs

unsigned-missing-sig-fixture

Test fixture (F.09) — SKILL.md without an accompanying .sig file. Default install rejects with exit 2; --allow-unsigned --rationale="..." proceeds.

★ 0
MILTONADINA
MILTONADINA/DevOPs

unsigned-mismatched-sig-fixture

Test fixture (F.09) — SKILL.md whose accompanying .sig signs different content. NFR-F3 hash check catches this even with --allow-unsigned.

★ 0
MILTONADINA
MILTONADINA/DevOPs

karpathy-guidelines

Behavioral guidelines that reduce common LLM coding mistakes. Apply whenever writing, modifying, or reviewing code. Don't assume requirements, don't overcomplicate, don't refactor unrelated code, and define success criteria before implementing. Use this skill on every non-trivial coding task to avoid bloat, silent assumptions, and completion-bias.

★ 0
MILTONADINA
MILTONADINA/DevOPs

webhook-idempotency

Defend against double-processing of webhook events across every provider (Stripe, GitHub, Slack, Twilio, SendGrid). Idempotency-key pattern + replay-window enforcement + dedupe-storage strategy. Triggers on any webhook handler authoring (route matching /webhook(s)?/, Stripe-Signature / X-Hub-Signature-256 header references). Defense against OWASP ASI02 (Tool Misuse) -- a replayed webhook that re-triggers a destructive tool is the canonical control-flow-level replay attack. Universal across providers; stack-specific signature verification lives in stack-specific skills.

★ 0
MILTONADINA
MILTONADINA/DevOPs

semgrep-scan

Run Semgrep static analysis to detect insecure code patterns - SQL injection, XSS, path traversal, weak crypto, broken auth, OWASP Top 10 issues. Use on every file change touching security-sensitive code and as part of the tiered security gate. Complements gitleaks (which catches secrets) by catching insecure logic.

★ 0