Core
Responses, errors and cookies
Content negotiation for errors, error views, and signed cookies.
#Responses and errors
Errors thrown in a route (throw new NotFoundError(), any HttpError, or an unexpected exception) become JSON or an HTML page, depending on who is asking:
- an explicit
Acceptheader decides (a browser asks fortext/html, an API client forapplication/json); - with no preference (no header, or
*/*, which is whatcurlandfetch()send) the request decides: anything under/api, a request withX-Requested-With: XMLHttpRequest, or a request with a JSON body gets JSON.req.wantsJsontells your own code the same.
JSON errors look like { "error": "Not found", "requestId": "…" } (plus details for validation errors). HTML errors use views/<status>.eta (404.eta, 500.eta), then views/error.eta, then a built-in page. The views receive { status, message, requestId }. A view that fails to render falls back to the built-in page, so one error never turns into another. In production the message of a 5xx is always Internal error.
#Cookies
req.cookies is always available. Set cookies.secret (or the COOKIE_SECRET environment variable; at least 16 characters) to sign cookies:
res.secureCookie('sid', id, { signed: true, maxAge: 7 * 86_400_000 }); // httpOnly, sameSite=lax, secure in production
const sid = req.signedCookies.sid; // the value; false when the signature does not match; undefined when absentA list of secrets rotates them: the first signs, all of them verify. signed: true without a secret throws instead of silently setting an unsigned cookie.