Skip to content

@edgetime/http

Problem-details errors, size-limited body readers, validation, cookies, conditional and range requests. No dependencies.

npm install @edgetime/http

HTTP building blocks on the Fetch API: errors, body readers, cookies, conditional requests and validation. No dependencies, and no dependency on the router.

import { errorHandler, HttpError } from '@edgetime/http';
throw new HttpError(404, 'No such order'); // the status must be 400 to 599
throw new HttpError(429, { detail: 'Slow down', headers: { 'retry-after': '60' } });
router.onError(
errorHandler({
report: (error, c) => log.error('request failed', { error }),
extensions: (c) => ({ requestId: c.get('requestId') }),
}),
);

errorHandler() answers with RFC 9457 problem details (application/problem+json):

  • An HttpError is sent as written, including its detail, headers and extensions.
  • Any other error with a status from 400 to 599 keeps that status. Its message is not sent, and of its headers only Allow, Retry-After and WWW-Authenticate are kept.
  • Everything else becomes 500 with a generic title.
  • report is called for every 5xx.
  • A report, extensions, map or body callback that throws is ignored; the response keeps its status and headers.
  • Responses carry Cache-Control: no-store unless the error sets its own cache-control header.
  • map(error, c) translates your own error types into an HttpError before rendering; return undefined to leave an error alone. report still receives the original.
  • unexpectedStatus: 503 answers 503 instead of 500 for an error that names no status. Any value other than 500 or 503 throws when the handler is created.
  • A callback that returns a promise, or the wrong kind of value, is ignored like one that throws: map must return an HttpError, extensions a plain object and body a value.

To keep a different error shape, pass body. It receives the problem document and returns the JSON to send; the status and headers are unchanged.

errorHandler({ body: (problem) => ({ error: problem.detail ?? problem.title }) });

readBytes, readText, readJson and readForm take a request or response and { limit }. The limit is in bytes and defaults to DEFAULT_BODY_LIMIT (1 MiB). A larger body is refused with 413, checked against Content-Length first and then against the bytes actually read. Invalid UTF-8 and malformed JSON are 400; a limit that is not a number throws; readJson and readForm answer 415 for the wrong content type.

validate, parseJson and parseQuery accept any Standard Schema validator, such as Zod 4, Valibot or ArkType. A failure throws 422 with each issue listed under errors as { path, message }. At most 100 issues are listed, with long messages cut; the number left out is given as moreErrors.

import { parseJson } from '@edgetime/http';
import { z } from 'zod';
const input = await parseJson(c.req, z.object({ title: z.string().min(1) }), { limit: 16 * 1024 });

queryObject(params) turns search parameters into an object, with repeated keys as arrays.

parseCookies(header), getCookie(request, name), serializeCookie(name, value, options) and expireCookie(name, options). Cookies are HttpOnly, Secure, SameSite=Lax and Path=/ unless the options say otherwise. serializeCookie percent-encodes a value that a cookie cannot carry as is. It throws on an invalid name, path, domain, sameSite or maxAge, on SameSite=None or Partitioned without Secure, and on a __Host- or __Secure- name, in any letter case, whose attributes break the prefix rules.

Export Purpose
etagMatches(ifNoneMatch, etag) Weak comparison of an If-None-Match header.
isNotModified(request, validators) Whether a GET or HEAD can be answered with 304.
notModified(validators, headers?) The 304 response.
parseRange(header, size) A single byte range as { offset, length }, 'unsatisfiable' for 416, or undefined to serve the whole body. size must be a non-negative whole number.

json, text, html, noContent and redirect build responses. withHeaders(response, change) edits headers on any response, copying it first when its headers are immutable. The copy keeps the original’s url. appendVary adds to Vary without duplicating.


Source: packages/http on GitHub.