↑ ↓ to move · Enter to open · Esc to close

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:

  1. an explicit Accept header decides (a browser asks for text/html, an API client for application/json);
  2. with no preference (no header, or */*, which is what curl and fetch() send) the request decides: anything under /api, a request with X-Requested-With: XMLHttpRequest, or a request with a JSON body gets JSON. req.wantsJson tells 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:

js
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 absent

A 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.