Build RFC 9457 problem details error responses
Return consistent, machine-readable API errors using the application/problem+json format.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function problem(status, title, { type = "about:blank", detail, instance, ...extensions } = {}) {
const body = { type, title, status, ...(detail && { detail }), ...(instance && { instance }), ...extensions };
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/problem+json" },
});
}Example / expected output
return problem(422, "Validation failed", {
detail: "The email field is not valid.",
errors: [{ field: "email", message: "Invalid email" }],
});How it works
RFC 9457 (which replaces RFC 7807) standardizes error bodies with type, title, status, detail and instance, plus any extra members you need. Clients can then handle errors generically. Keep detail free of stack traces and internal information.
Related snippets
- TypeScript Tested
Assert a value is not null or undefined
An assertion function that narrows away null and undefined and throws a clear error otherwise.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Respect Retry-After on 429 and 503 responses
Retry rate-limited requests after the delay the server asks for, instead of guessing.
- JavaScript Tested
Parse the Link header for pagination
Extract next, prev, first and last page URLs from an RFC 8288 Link header like GitHub's API returns.

