Errors Are a Contract: API Routes
Updated
IntermediateWhat you'll learn
~30 min- Build response helpers that give every route one success and one error envelope
- Return only a safe error to the client and keep the real error in the server log
- Cap page size at a limit you choose and handle async params in route handlers
- Prove with a test that an induced failure on every route leaks no stack frame and no SQL fragment
An error is part of the API
Clients depend on the shape of your errors as much as on the shape of your successes. A route that returns { results } where others return { data } breaks a hook. A route that forwards a database error message hands a stranger your table names. Both are the same mistake: the response was left to whoever wrote the handler.
The reference app (Next.js, any OIDC identity provider, SQL Server, containers) fixes this with a few helpers in @/lib/response and one rule: an error the client sees is a decision someone made, never an exception someone forwarded. Everything below is the reference app’s pattern; each row says what your agency may set differently.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| Inconsistent response shapes | Helpers: listResponse, errorResponse, plus SafeError; the alternative is a shared OpenAPI schema with generated clients | Same on every platform | Where the envelope is defined |
| Internal detail leaks to clients | Only a SafeError’s static message is sent; everything else becomes a generic 500 and a correlation id; the alternative is Problem Details (RFC 9457) responses | 34: the log line lands in Application Insights · 35: CloudWatch Logs · 36: Cloud Logging | Which error format your consumers expect |
| Unbounded list queries | Page size capped at 500, default 25; the alternative is cursor pagination or a different cap | Same on every platform | The cap, from your own measurements |
| Request parameters in route handlers | Awaited params (not optional in the pinned Next major) | Same on every platform | Nothing; this is a framework fact |
The 500 and the 25 are the reference app’s numbers, not a standard. Set your own and keep them in one constant.
The helpers
REFERENCE CODE src/lib/response.ts: response envelopes, SafeError, log allowlist, and page-size clamping open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { randomUUID } from "node:crypto";import { NextResponse } from "next/server";
export const MAX_PAGE_SIZE = 500; // reference choice: set your ownexport const DEFAULT_PAGE_SIZE = 25;
const CODES: Record<number, string> = { 400: "BAD_REQUEST", 401: "UNAUTHENTICATED", 403: "FORBIDDEN", 404: "NOT_FOUND", 409: "CONFLICT", 422: "VALIDATION_ERROR", 500: "INTERNAL_ERROR",};
// The only error whose message reaches the client. Write static strings.// Never build one from another error's message.export class SafeError extends Error { constructor(message: string, readonly status: number = 400, readonly code?: string) { super(message); this.name = "SafeError"; }}
export function errorResponse(message: string, status: number, code?: string, correlationId?: string) { return NextResponse.json( { error: { code: code ?? CODES[status] ?? "ERROR", message, ...(correlationId ? { correlationId } : {}) } }, { status }, );}
export function listResponse<T>(rows: T[], m: { page: number; pageSize: number; total: number }) { return NextResponse.json({ data: rows, meta: { ...m, totalPages: Math.max(1, Math.ceil(m.total / m.pageSize)) }, });}
export function singleResponse<T>(item: T, status = 200) { return NextResponse.json({ data: item }, { status });}
// Error classes safe to write to a log by name. Anything else is logged as "UnclassifiedError".// Extend this list from your own drivers; never log a message or a stack to fill a gap in it.const LOGGABLE_CLASSES = new Set([ "Error", "TypeError", "RangeError", "SyntaxError", "AbortError", "TimeoutError", "ZodError", "ConnectionError", "RequestError", "TransactionError", "PreparedStatementError", // mssql]);// Driver codes look like ELOGIN, ETIMEOUT, ESOCKET. Anything else is dropped.const SAFE_CODE = /^[A-Z][A-Z0-9_]{1,31}$/;
export function safeDiagnostics(err: unknown): { errorClass: string; code?: string } { const name = err instanceof Error ? err.name : typeof err; const errorClass = LOGGABLE_CLASSES.has(name) ? name : "UnclassifiedError"; const raw = (err as { code?: unknown } | null)?.code; return typeof raw === "string" && SAFE_CODE.test(raw) ? { errorClass, code: raw } : { errorClass };}
// The one place an exception becomes a response.export function fail(route: string, err: unknown) { if (err instanceof SafeError) return errorResponse(err.message, err.status, err.code); const correlationId = randomUUID(); // Allowlisted fields only. No err.message, no err.stack, no err.cause: a database or provider // error can carry SQL text, bound values or URLs. The correlation id is how support finds this line. console.error(JSON.stringify({ event: "route_error", route, correlationId, ...safeDiagnostics(err) })); return errorResponse("Something went wrong. Try again or contact support.", 500, undefined, correlationId);}
// Whole-string digits only: parseInt("12junk") is 12, and a validator must not agree.const DIGITS = /^\d{1,10}$/;
export function clampPageSize(raw: string | null): number { if (raw === null || !DIGITS.test(raw)) return DEFAULT_PAGE_SIZE; const n = Number(raw); if (n < 1) return DEFAULT_PAGE_SIZE; return Math.min(n, MAX_PAGE_SIZE);}fail() never logs the exception object. The log line carries the route, a correlation id, an allowlisted error class and an allowlisted driver code such as ELOGIN; the same id goes back to the client in error.correlationId, so a caller who reports “it failed” gives support one string that finds the line. The full error is not in the log at all. If you need it to debug, reproduce locally or add a field to the allowlist on purpose.
SafeError is the same class Lesson 3 throws for a missing session and Lesson 5 throws for a denial; fail() is what turns it into a response. Lesson 3 and Lesson 5 only assumed this file. Now it exists.
console.error writes one JSON line with the route, correlation id, error class and driver code. Lesson 16 sends those logs to telemetry. Neither the client nor the log sees the error message or stack, because database and provider errors can carry SQL text, bound values and URLs; a person debugging starts from the correlation id the client reported.
Plan the change with your agent
Open your workspace agent at the project root with the vehicle-fleet feature from Lesson 6 and src/lib/response.ts in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and ask:
Read src/lib/response.ts and our vehicle-fleet API routes, and plan the collection and single-item endpoints so every response uses our envelope, clamps page size, and never leaks internal error details. Ask anything unclear.What to check in the plan before you approve
src/app/api/vehicle-fleet/route.tswrapsGETandPOSTinwithPermission(), runs parameterized queries throughwithPool((pool) => ...), clampspageSizewithclampPageSize(), and returnslistResponse()orsingleResponse().POSTvalidates withVehicleFleetCreateSchema.safeParse(), returns422(VALIDATION_ERROR) withz.flattenError(parsed.error).fieldErrorson failure, and passes onlyparsed.dataplussession.sub(created_by) to SQL.src/app/api/vehicle-fleet/[id]/route.tsawaitsctx.params, validates the wholeidstring as digits withRouteIdSchema(neverparseInt), throwsSafeError("Invalid id", 400)orSafeError("Vehicle not found", 404), and performs soft delete (status = 'inactive').- Handlers do not catch errors locally to forward
err.message; unhandled errors pass throughwithPermission()tofail().
If the agent’s initial plan uses parseInt on route params or catches errors inside the handler, nudge it before approving:
Validate the route id with a whole-string digit schema instead of parseInt, and let withPermission pass errors to fail().What you get
- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/lib/response.ts and our vehicle-fleet API routes, and plan the collection and single-item endpoints so every response uses our envelope, clamps page size, and never leaks internal error details. Ask anything unclear.
- The tool replies: Proposed plan: 1. src/app/api/vehicle-fleet/route.ts: GET with clampPageSize(), OFFSET/FETCH and COUNT via withPool(), returning listResponse(); POST with VehicleFleetCreateSchema.safeParse(), 422 fieldErrors on failure, and parameterized INSERT returning singleResponse(..., 201). 2. src/app/api/vehicle-fleet/[id]/route.ts: GET, PUT, and soft-DELETE awaiting ctx.params, throwing SafeError 400 on bad id or 404 when missing. 3. Both files rely on withPermission() and fail() with no local try/catch. How should we validate the [id] segment, and what does DELETE set on the row?
- You type in the session: Validate the route id with a whole-string digit schema instead of parseInt, and make DELETE set status to inactive. Build it.
- The tool replies: Done. - src/lib/response.ts: SafeError, errorResponse, listResponse, singleResponse, fail, clampPageSize - src/app/api/vehicle-fleet/route.ts: GET and POST inside withPermission(); no try/catch in either - src/app/api/vehicle-fleet/[id]/route.ts: GET, PUT, DELETE; each awaits ctx.params before using the id Validation failures return 422 with field errors only. Every SQL statement uses request.input().
- You type in the session: What does a client see if the database is down?
- The tool replies: withPool throws inside the handler (a login failure first gets one refresh and one retry; Lesson 8). withPermission catches it and calls fail(). The error is not a SafeError, so fail() logs one line with the route, a correlation id, the error class and driver code, and returns a 500 with the generic message, code INTERNAL_ERROR and that correlation id. The client gets no driver message, no table name and no stack, and the log has none either. One gap in what I wrote: if a handler throws outside withPermission, for example at import time, none of this runs. That path is Next's default error handling, and I have not verified what it returns in a production build.
- You type in the session: Then test it properly: break every route and look at what comes back.
- The tool replies: Created tests/contract/errors.test.ts. It discovers every route file the same way the RBAC test does, mocks the session as superadmin, and mocks the database module so every query throws an error whose message contains a SQL statement and a table name, and whose stack contains file paths. It calls every exported handler with a valid body where one is needed, and a params promise where the path has a segment in brackets. For each response it asserts: status 500, the generic envelope, a correlation id, no stack frame, no path, no SQL keyword from the planted message, and no table name. It also captures what was written to the server log and asserts the same planted text is absent there, and that the logged correlation id matches the one in the response. It also fails if a route has no entry in the fixtures file, so a new route cannot skip the test.
- You type in the session: Now make a handler leak on purpose, to see the test catch it.
- The tool replies: I changed the PUT handler to return errorResponse(err.message, 500) and reran: 1 failed: PUT /api/vehicle-fleet/[id] leaked the planted SQL text: Invalid object name 'dbo.vehicle_fleet'. Reverted; all passed.
Illustrative session in Claude Code; the exact wording varies.
The routes
REFERENCE CODE src/app/api/vehicle-fleet/route.ts: collection GET and POST handlers using the response contract open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import sql from "mssql";import { withPermission } from "@/lib/auth/with-permission";import { withPool } from "@/lib/db/pool";import { VehicleFleetCreateSchema } from "@/types/vehicle-fleet";import { clampPageSize, listResponse, singleResponse } from "@/lib/response";import { z } from "zod";
export const GET = withPermission("vehicle-fleet", "read", async (req) => { const sp = req.nextUrl.searchParams; const page = Math.max(1, Number.parseInt(sp.get("page") ?? "1", 10) || 1); const pageSize = clampPageSize(sp.get("pageSize")); const status = sp.get("status");
const { rows, total } = await withPool(async (pool) => { const list = await pool.request() .input("status", sql.NVarChar(20), status) .input("offset", sql.Int, (page - 1) * pageSize) .input("size", sql.Int, pageSize) .query(`SELECT * FROM vehicle_fleet WHERE (@status IS NULL OR status = @status) ORDER BY id OFFSET @offset ROWS FETCH NEXT @size ROWS ONLY`); const count = await pool.request() .input("status", sql.NVarChar(20), status) .query(`SELECT COUNT(*) AS n FROM vehicle_fleet WHERE (@status IS NULL OR status = @status)`); return { rows: list.recordset, total: count.recordset[0].n as number }; }); return listResponse(rows, { page, pageSize, total });});
export const POST = withPermission("vehicle-fleet", "create", async (req, session) => { const parsed = VehicleFleetCreateSchema.safeParse(await req.json()); if (!parsed.success) { // Field errors only: no input echoed back, no internal paths. return Response.json( { error: { code: "VALIDATION_ERROR", message: "Invalid request", fields: z.flattenError(parsed.error).fieldErrors } }, { status: 422 }, ); } const d = parsed.data; const result = await withPool((pool) => pool.request() .input("vehicle_id", sql.NVarChar(20), d.vehicle_id) .input("make", sql.NVarChar(50), d.make) .input("created_by", sql.NVarChar(100), session.sub) .query(`INSERT INTO vehicle_fleet (vehicle_id, make, created_by) OUTPUT INSERTED.* VALUES (@vehicle_id, @make, @created_by)`)); return singleResponse(result.recordset[0], 201);});Only parsed.data reaches SQL: Zod drops unknown fields, so extra keys in the body never become columns, and the query uses request.input() rather than string building. The validation branch builds its own body because it carries field errors, and it still contains no input values.
Async params in route handlers
In the pinned Next major, the route context’s params is a promise. Reading it without await is an error, not a deprecation.
REFERENCE CODE src/app/api/vehicle-fleet/[id]/route.ts: single-item handler awaiting route params open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { withPermission } from "@/lib/auth/with-permission";import { withPool } from "@/lib/db/pool";import sql from "mssql";import { SafeError, singleResponse } from "@/lib/response";import { RouteIdSchema } from "@/lib/route-id";
type Ctx = { params: Promise<{ id: string }> };
export const GET = withPermission<Ctx>("vehicle-fleet", "read", async (_req, _session, ctx) => { const { id } = await ctx.params; const parsedId = RouteIdSchema.safeParse(id); if (!parsedId.success) throw new SafeError("Invalid id", 400); // static message: nothing from the input const n = parsedId.data;
const r = await withPool((pool) => pool.request().input("id", sql.Int, n).query("SELECT * FROM vehicle_fleet WHERE id = @id")); if (r.recordset.length === 0) throw new SafeError("Vehicle not found", 404); return singleResponse(r.recordset[0]);});Here is the reference ID schema in src/lib/route-id.ts that your agent writes to validate whole-string numeric route parameters:
import { z } from "zod";
// The whole string must be 1-10 digits and fit a SQL Server int. parseInt would accept "12junk" as 12.export const RouteIdSchema = z .string() .regex(/^\d{1,10}$/) .transform(Number) .refine((n) => n >= 1 && n <= 2_147_483_647);Two tools help when an AI tool writes the old form. npx next typegen generates route-context types, and the codemod npx @next/codemod@canary next-async-request-api . rewrites synchronous access. Query strings are different: req.nextUrl.searchParams is not a promise.
Look for three things in generated routes: err.message inside a response, string concatenation in SQL, and a handler exported without withPermission(). The first two are leaks; the third is Lesson 5’s test. A prompt that says “never put err.message in a response” prevents the first; the test below proves it.
Prove it
The test induces a failure on every route and inspects what the client would receive.
REFERENCE TEST tests/contract/errors.test.ts: contract test inducing database failures across every route open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { readdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { describe, it, expect, vi } from "vitest";import { NextRequest } from "next/server";import { FIXTURES } from "./error-fixtures";
const PLANTED = "Invalid object name 'dbo.vehicle_fleet'. SELECT secret_col FROM dbo.vehicle_fleet";
vi.mock("@/lib/db/pool", () => ({ withPool: async () => { throw Object.assign(new Error(PLANTED), { stack: `Error: ${PLANTED}\n at Request.query (/srv/app/node_modules/mssql/lib/base/request.js:1:1)` }); },}));vi.mock("@/lib/auth/session", () => ({ requireSession: async () => ({ id: "s", sub: "u1", issuer: "http://localhost:8080/default", roles: ["Intake.SuperAdmin"], name: "Test" }),}));const logged: string[] = [];vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { logged.push(args.map(String).join(" ")); });
const API = join(process.cwd(), "src/app/api");const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
const routes = (readdirSync(API, { recursive: true }) as string[]) .filter((f) => /(^|[\\/])route\.ts$/.test(f) && !f.startsWith("auth") && !f.startsWith("health")) .flatMap((f) => { const src = readFileSync(join(API, f), "utf8"); const path = "/api/" + f.replaceAll("\\", "/").replace(/\/?route\.ts$/, ""); return METHODS.filter((m) => new RegExp(`export\\s+(const|async function)\\s+${m}\\b`).test(src)) .map((m) => ({ key: `${m} ${path}`, file: f, method: m, path })); });
describe.each(routes)("$key", ({ key, file, method, path }) => { it("has a fixture so it cannot skip this test", () => { expect(FIXTURES[key], `route ${key} needs an entry in error-fixtures.ts`).toBeDefined(); });
it("leaks nothing when the database fails", async () => { logged.length = 0; const mod = await import(`@/app/api/${file.replaceAll("\\", "/")}`); const params = Object.fromEntries([...path.matchAll(/\[(\w+)\]/g)].map((m) => [m[1], "1"])); const url = "http://localhost" + path.replace(/\[(\w+)\]/g, "1"); const f = FIXTURES[key]; const req = new NextRequest(url, { method, ...(f?.body ? { body: JSON.stringify(f.body), headers: { "content-type": "application/json" } } : {}) }); const res: Response = await mod[method](req, { params: Promise.resolve(params) });
const text = await res.text(); expect(res.status).toBe(500); const body = JSON.parse(text); expect(body.error.code).toBe("INTERNAL_ERROR"); expect(body.error.correlationId).toMatch(/^[0-9a-f-]{36}$/); // The server log gets the same treatment: no message, no SQL, no stack, same correlation id. const log = logged.join("\n"); expect(log).toContain(body.error.correlationId); expect(log).not.toContain("Invalid object name"); expect(log).not.toMatch(/\bdbo\b|secret_col|vehicle_fleet/i); expect(log).not.toMatch(/\n\s+at |node_modules|\.(ts|js):\d+/); expect(text).not.toContain("Invalid object name"); expect(text).not.toMatch(/\bdbo\b|secret_col|vehicle_fleet/i); expect(text).not.toMatch(/\n\s+at |node_modules|\.(ts|js):\d+/); });});error-fixtures.ts maps each route key to a valid body when the route takes one, so the request gets past validation and reaches the database call that fails. A route with no fixture entry fails the first test; that is how a new route is kept from skipping the check.
The planted fault is the one in the session above: make a handler return err.message and the second test must fail with the planted SQL text. A second planted fault covers the log: change fail() to console.error(route, err) and the same test must fail on the log assertions. Run each once and keep the failing output.
Two more negative tests cover the other fixes. One proves the log allowlist drops what it does not recognise; the other proves a partly numeric id is refused before any query runs:
REFERENCE TEST tests/unit/response-hardening.test.ts: unit tests for log hygiene and whole-string ID validation open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { describe, it, expect, vi } from "vitest";import { fail, safeDiagnostics, clampPageSize, DEFAULT_PAGE_SIZE } from "@/lib/response";import { RouteIdSchema } from "@/lib/route-id";
describe("fail() log hygiene", () => { it("logs no message, stack or cause, and drops an unlisted class and a hostile code", () => { const lines: string[] = []; vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(" ")); }); class VendorSecretError extends Error { code = "select * from users"; } const err = new VendorSecretError("connect failed https://db.internal:1433 password=hunter2", { cause: new Error("SELECT 1") }); const res = fail("GET /api/x", err); const log = lines.join("\n"); expect(res.status).toBe(500); expect(log).not.toMatch(/hunter2|db\.internal|SELECT|select \*|VendorSecretError|\n\s+at /); expect(safeDiagnostics(err)).toEqual({ errorClass: "UnclassifiedError" }); });});
describe("whole-string id validation", () => { it.each(["12junk", "1e3", "0x10", " 12", "12 ", "-1", "0", "1.5", "", "99999999999"])("refuses %j", (raw) => { expect(RouteIdSchema.safeParse(raw).success).toBe(false); }); it("accepts a plain id", () => expect(RouteIdSchema.parse("12")).toBe(12)); it("treats a partly numeric page size as junk", () => expect(clampPageSize("12junk")).toBe(DEFAULT_PAGE_SIZE));});For the route itself, add a fixture-driven case to errors.test.ts: a request to /api/vehicle-fleet/12junk returns 400 with Invalid id, and the mocked withPool is never called.
It proves the path where the database call throws. It does not prove every failure a route could have. Add a fixture and an assertion for each other failure your routes can reach, such as an upstream service timing out, and keep this one as the baseline.
Pagination: a cap you choose
A list with no bound can freeze a browser tab or time out a query. The cap is the reference app’s judgment call: it chose 500 and a default of 25. Your cap should come from measuring your rows through your grid, and the constant lives in @/lib/response so a change is one edit. Here is the reference unit test your agent writes for clampPageSize():
import { describe, it, expect } from "vitest";import { clampPageSize, MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE } from "@/lib/response";
describe("clampPageSize", () => { it("caps a large request", () => expect(clampPageSize("2000")).toBe(MAX_PAGE_SIZE)); it("defaults on junk", () => expect(clampPageSize("abc")).toBe(DEFAULT_PAGE_SIZE)); it("defaults on zero and negative", () => { expect(clampPageSize("0")).toBe(DEFAULT_PAGE_SIZE); expect(clampPageSize("-5")).toBe(DEFAULT_PAGE_SIZE); });});Offset pagination is the reference pattern because it is simple and fits administrative data. High-volume streams, such as telemetry or audit logs, are a case where a cursor is the usual alternative.
A GET with pageSize=2000 returns 500 rows and no error. What is happening, and where should the number 500 live?
Your induced-failure test passes for all routes except one, which returns the database's error text inside a 500 body. The handler has its own try/catch with errorResponse(err.message, 500). What is the fix?
Key takeaway
Put the response envelope in helpers, send the client only a SafeError’s static message, and let fail() log everything else and return a generic 500. Validate path ids as whole strings, never with parseInt. Await params in route handlers, clamp page size with a constant you chose, and prove the contract by inducing a failure on every route and checking that no stack frame and no SQL fragment comes back. The 500-item cap and the envelope are the reference app’s choices: set your own, and keep them in one file.
- LEADERSHIP DECISION
- The page-size cap and the response envelope the agency standardises on, and who may change them.
- PRACTITIONER ACTION
- Induce a failure on every route and confirm no stack frame or SQL fragment reaches the response.
- SUCCESS MEASURE
- Audit finding avoided: no internal detail disclosed through an error response.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided