Response contracts
What you need to know
A response contract tells callers what happened using status, headers and a documented body. Consistent error shapes help callers recover without reading implementation details.
By the end, you can: set status and headers; specify negative method tests.
Create a response after a successful insert
// Partial response construction; insertion has already succeeded.export function createdBook(id: string) { return Response.json({ id }, { status: 201, headers: { Location: '/api/books/' + encodeURIComponent(id), 'Cache-Control': 'no-store' } });}Expected behavior (not framework-tested): A 201 response contains the newly created ID and the resource location; it does not itself perform the insertion.
How it works
Choose status codes according to the outcome. A successful read normally uses 200; a created resource can use 201 and a Location header; a successful operation with no representation can return 204 and no body. A client input error uses 400; absent authentication is generally 401 (with an appropriate challenge for HTTP authentication); a known denied caller may receive 403; missing data uses 404; conflicts can use 409. An application may intentionally conceal private resource existence with 404. A 405 refers to a method not supported by the endpoint, not a missing record.
Use Response.json to serialize JSON and set the JSON content type. NextResponse adds framework-specific helpers, for example response cookies and redirect utilities; it is not required for ordinary JSON. An HTTP Cache-Control header addresses HTTP intermediaries/browser caching; it does not replace a Next.js fetch policy. For private responses use a suitable no-store policy and test actual headers; avoid leaking internal errors, credentials or stack traces.
A successful no-content result
export function deletedBook() { return new Response(null, { status: 204 });}export function invalidBook() { return Response.json({ error: 'INVALID_BOOK' }, { status: 400 });}Expected behavior (not framework-tested): 204 has no response body; 400 includes a stable machine-readable error code.
Common mistake
Returning JSON with HTTP 200 for every error forces clients to guess whether an operation succeeded. Conversely, do not return a JSON body with 204. Validate response status, headers and content independently, including unexpected exceptions and unsupported methods.
Practice and verification
Write a contract matrix for GET, POST and PATCH: success, malformed body, denied access, conflict and missing item. For each row include expected status, JSON shape or no-body requirement and cache policy. Check that internal notes are never part of a public DTO.
Scope: App Router, proposed Next.js 16.x, Cache Components disabled for these labs. Snippets assume a reviewed TypeScript app and are static examples; framework behavior has not been executed. Exact supported patch and dependency set must be verified before running.