vael:http
Go-style HTTP/1.1 server, ServeMux router, middleware, and immutable request/response types.
Available in the vjs (vaeljs) runtime only; absent in vjs-lite.
Provides Go 1.22+ ServeMux pattern routing, composable middleware,
immutable HttpRequest / HttpResponse objects, zero-socket .fetch()
dispatch, and a hyper / tokio HTTP/1.1 server via serve().
import ... from "vael:http"
vael-http (enabled by default in vaeljs-core; absent in vaeljs-lite-core)Example
Section titled “Example”import { createRouter, json, recover, requestId } from "vael:http";
const router = createRouter();router.use(recover(), requestId());router.get("/users/{id}", (req) => { return json({ id: req.param("id") });});
const res = await router.fetch("/users/42");console.log(res.status, res.json());createRoutervjs onlyv0.0.0-alpha.0ServeMux router instance.responsevjs onlyv0.0.0-alpha.0HttpResponse.jsonvjs onlyv0.0.0-alpha.0HttpResponse (content-type: application/json; charset=utf-8).htmlvjs onlyv0.0.0-alpha.0HttpResponse (content-type: text/html; charset=utf-8).textvjs onlyv0.0.0-alpha.0HttpResponse (content-type: text/plain; charset=utf-8).redirectvjs onlyv0.0.0-alpha.0HttpResponse (default 302).noContentvjs onlyv0.0.0-alpha.0204 No Content HttpResponse.setCookievjs onlyv0.0.0-alpha.0HttpResponse with an RFC 6265 / CRLF-safe Set-Cookie header appended.httpErrorvjs onlyv0.0.0-alpha.0HttpError.badRequestvjs onlyv0.0.0-alpha.0400 Bad Request HttpError.unauthorizedvjs onlyv0.0.0-alpha.0401 Unauthorized HttpError.forbiddenvjs onlyv0.0.0-alpha.0403 Forbidden HttpError.notFoundvjs onlyv0.0.0-alpha.0404 Not Found HttpError.conflictvjs onlyv0.0.0-alpha.0409 Conflict HttpError.methodNotAllowedvjs onlyv0.0.0-alpha.0405 Method Not Allowed HttpError with optional Allow methods.recovervjs onlyv0.0.0-alpha.0HttpError to its response and unexpected throws to 500.requestIdvjs onlyv0.0.0-alpha.0x-request-id on ctx.state.requestId and the response.loggervjs onlyv0.0.0-alpha.0securityHeadersvjs onlyv0.0.0-alpha.0x-content-type-options, x-frame-options, and referrer-policy defaults.corsvjs onlyv0.0.0-alpha.0Access-Control-* response headers.composevjs onlyv0.0.0-alpha.0Middleware.servevjs onlyv0.0.0-alpha.0hyper and tokio::net::TcpListener.parseCookiesvjs onlyv0.0.0-alpha.0Cookie request header into { name: value } pairs.formatSetCookievjs onlyv0.0.0-alpha.0Set-Cookie header value.HttpRequestvjs onlyv0.0.0-alpha.0HttpResponsevjs onlyv0.0.0-alpha.0HttpErrorvjs onlyv0.0.0-alpha.0ServeMux and recover().ServeMuxvjs onlyv0.0.0-alpha.0ServeMux-style HTTP router with middleware, route groups, traversal-safe static file serving, and zero-socket .fetch() testing.QueryParamsvjs onlyv0.0.0-alpha.0application/x-www-form-urlencoded parameter bag.AbortSignalLikevjs onlyv0.0.0-alpha.0serve({ signal }).ResponseInitvjs onlyv0.0.0-alpha.0response, json, html, text, and noContent.SetCookieOptionsvjs onlyv0.0.0-alpha.0setCookie and formatSetCookie.RequestContextvjs onlyv0.0.0-alpha.0HttpRequest to handlers and middleware.StaticOptionsvjs onlyv0.0.0-alpha.0ServeMux.static(urlPrefix, rootDir, options).FetchInputvjs onlyv0.0.0-alpha.0ServeMux.fetch(input, init).FetchInitvjs onlyv0.0.0-alpha.0ServeMux.fetch(input, init).RecoverOptionsvjs onlyv0.0.0-alpha.0recover().RequestIdOptionsvjs onlyv0.0.0-alpha.0requestId().LogEntryvjs onlyv0.0.0-alpha.0logger({ sink }).LoggerOptionsvjs onlyv0.0.0-alpha.0logger().SecurityHeadersOptionsvjs onlyv0.0.0-alpha.0securityHeaders().CorsOptionsvjs onlyv0.0.0-alpha.0cors().ServeOptionsvjs onlyv0.0.0-alpha.0serve(options, handlerOrMux).Servervjs onlyv0.0.0-alpha.0serve().HeadersInitvjs onlyv0.0.0-alpha.0[name, value] pairs.RedirectStatusvjs onlyv0.0.0-alpha.0SameSitePolicyvjs onlyv0.0.0-alpha.0Set-Cookie SameSite policy attribute.Handlervjs onlyv0.0.0-alpha.0HttpResponse (synchronously or as a Promise).Middlewarevjs onlyv0.0.0-alpha.0Handler.Functions
Section titled “Functions”createRouter
Section titled “createRouter”export function createRouter(): ServeMux;
Create a new ServeMux router instance.
ServeMux — New empty ServeMux router.import { createRouter, json } from "vael:http";
const router = createRouter();router.get("/", () => json({ hello: "vael" }));const res = await router.fetch("/");console.log(res.json());response
Section titled “response”export function response(body?: string | Uint8Array | null, init?: ResponseInit): HttpResponse;
Create an immutable HttpResponse.
| Name | Type | Description |
|---|---|---|
body optional | string | Uint8Array | null | Optional response body string, bytes, or null. |
init optional | ResponseInit | Optional status code and headers. |
HttpResponse — Immutable HttpResponse.TypeError— on invalid status code or unsafe header values.
export function json(data: unknown, init?: ResponseInit): HttpResponse;
Create an immutable JSON HttpResponse (content-type: application/json; charset=utf-8).
| Name | Type | Description |
|---|---|---|
data | unknown | JSON-serializable value. |
init optional | ResponseInit | Optional status code and headers. |
HttpResponse — Immutable JSON HttpResponse.import { json } from "vael:http";
const res = json({ ok: true }, { status: 201 });console.log(res.status, res.text());export function html(body: string, init?: ResponseInit): HttpResponse;
Create an immutable HTML HttpResponse (content-type: text/html; charset=utf-8).
| Name | Type | Description |
|---|---|---|
body | string | HTML body string. |
init optional | ResponseInit | Optional status code and headers. |
HttpResponse — Immutable HTML HttpResponse.export function text(body: string, init?: ResponseInit): HttpResponse;
Create an immutable plain-text HttpResponse (content-type: text/plain; charset=utf-8).
| Name | Type | Description |
|---|---|---|
body | string | Plain-text body string. |
init optional | ResponseInit | Optional status code and headers. |
HttpResponse — Immutable plain-text HttpResponse.redirect
Section titled “redirect”export function redirect(location: string, status?: RedirectStatus): HttpResponse;
Create an immutable redirect HttpResponse (default 302).
| Name | Type | Description |
|---|---|---|
location | string | Target Location header URL or path (CRLF-free). |
status optional | RedirectStatus | Redirect status code (301, 302, 303, 307, or 308, default 302). |
HttpResponse — Immutable redirect HttpResponse.TypeError— on invalid status code or unsafelocation.
noContent
Section titled “noContent”export function noContent(init?: ResponseInit): HttpResponse;
Create an immutable 204 No Content HttpResponse.
| Name | Type | Description |
|---|---|---|
init optional | ResponseInit | Optional status/headers overrides (defaults to status 204). |
HttpResponse — Immutable empty HttpResponse.setCookie
Section titled “setCookie”export function setCookie(res: HttpResponse, cookie: SetCookieOptions): HttpResponse;
Return a new HttpResponse with an RFC 6265 / CRLF-safe Set-Cookie header appended.
| Name | Type | Description |
|---|---|---|
res | HttpResponse | Base immutable HttpResponse. |
cookie | SetCookieOptions | Cookie name, value, and attributes. |
TypeError— when cookie name, value, or attributes fail validation.
httpError
Section titled “httpError”export function httpError(status: number, message?: string, code?: string, details?: unknown): HttpError;
Construct an HttpError.
| Name | Type | Description |
|---|---|---|
status | number | HTTP status code (400..=599). |
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
details optional | unknown | Optional structured error details. |
HttpError — New HttpError instance.badRequest
Section titled “badRequest”export function badRequest(message?: string, code?: string): HttpError;
Construct a 400 Bad Request HttpError.
| Name | Type | Description |
|---|---|---|
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
unauthorized
Section titled “unauthorized”export function unauthorized(message?: string, code?: string): HttpError;
Construct a 401 Unauthorized HttpError.
| Name | Type | Description |
|---|---|---|
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
forbidden
Section titled “forbidden”export function forbidden(message?: string, code?: string): HttpError;
Construct a 403 Forbidden HttpError.
| Name | Type | Description |
|---|---|---|
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
notFound
Section titled “notFound”export function notFound(message?: string, code?: string): HttpError;
Construct a 404 Not Found HttpError.
| Name | Type | Description |
|---|---|---|
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
conflict
Section titled “conflict”export function conflict(message?: string, code?: string): HttpError;
Construct a 409 Conflict HttpError.
| Name | Type | Description |
|---|---|---|
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
methodNotAllowed
Section titled “methodNotAllowed”export function methodNotAllowed(allow?: string[], message?: string): HttpError;
Construct a 405 Method Not Allowed HttpError with optional Allow methods.
| Name | Type | Description |
|---|---|---|
allow optional | string[] | Optional list of allowed HTTP methods for the Allow header. |
message optional | string | Optional error message. |
recover
Section titled “recover”export function recover(options?: RecoverOptions): Middleware;
Middleware that converts HttpError to its response and unexpected throws to 500.
| Name | Type | Description |
|---|---|---|
options optional | RecoverOptions | Optional { onError } observer. |
Middleware — Composable Middleware function.requestId
Section titled “requestId”export function requestId(options?: RequestIdOptions): Middleware;
Middleware that propagates or generates a safe x-request-id on ctx.state.requestId and the response.
| Name | Type | Description |
|---|---|---|
options optional | RequestIdOptions | Optional { headerName, generator } configuration. |
Middleware — Composable Middleware function.logger
Section titled “logger”export function logger(options?: LoggerOptions): Middleware;
Middleware that logs request method, path, status, and duration.
| Name | Type | Description |
|---|---|---|
options optional | LoggerOptions | Optional { sink } configuration. |
Middleware — Composable Middleware function.securityHeaders
Section titled “securityHeaders”export function securityHeaders(options?: SecurityHeadersOptions): Middleware;
Middleware that attaches x-content-type-options, x-frame-options, and referrer-policy defaults.
| Name | Type | Description |
|---|---|---|
options optional | SecurityHeadersOptions | Optional header overrides or false flags to disable individual headers. |
Middleware — Composable Middleware function.export function cors(options?: CorsOptions): Middleware;
Middleware that handles CORS preflight requests and Access-Control-* response headers.
| Name | Type | Description |
|---|---|---|
options optional | CorsOptions | Optional CORS policy configuration. |
Middleware — Composable Middleware function.compose
Section titled “compose”export function compose(...middlewares: Middleware[]): Middleware;
Compose middleware functions left-to-right into a single Middleware.
| Name | Type | Description |
|---|---|---|
...middlewares | Middleware[] | Middleware functions to compose. |
Middleware — Combined Middleware function.export function serve(handlerOrMux: Handler | ServeMux): Server;
export function serve(options: ServeOptions, handlerOrMux: Handler | ServeMux): Server;
Start a live HTTP/1.1 server backed by hyper and tokio::net::TcpListener.
serve(handlerOrMux)| Name | Type | Description |
|---|---|---|
handlerOrMux | Handler | ServeMux | Request handler function or ServeMux router instance. |
Server — Running Server handle.serve(options, handlerOrMux)Start a live HTTP/1.1 server backed by hyper and tokio::net::TcpListener with explicit options.
| Name | Type | Description |
|---|---|---|
options | ServeOptions | Server bind host, port, body limit, and optional abort signal. |
handlerOrMux | Handler | ServeMux | Request handler function or ServeMux router instance. |
Server — Running Server handle.TypeError— on invalid handler/router; on invalid options or handler/router.Error— on bind failure.RangeError— whenportormaxBodyBytesis out of range.
import { createRouter, serve, text } from "vael:http";
const router = createRouter();router.get("/", () => text("ok"));const server = serve({ host: "127.0.0.1", port: 0 }, router);console.log(server.url);await server.close();parseCookies
Section titled “parseCookies”export function parseCookies(header: string): Record<string, string>;
Parse an HTTP Cookie request header into { name: value } pairs.
| Name | Type | Description |
|---|---|---|
header | string | Raw Cookie header value. |
Record<string, string> — Record mapping cookie names to decoded string values.formatSetCookie
Section titled “formatSetCookie”export function formatSetCookie(options: SetCookieOptions): string;
Format and validate an RFC 6265 / CRLF-safe Set-Cookie header value.
| Name | Type | Description |
|---|---|---|
options | SetCookieOptions | Cookie name, value, and attributes. |
string — Formatted Set-Cookie header string.TypeError— when cookie name, value, or attributes fail validation.
Classes
Section titled “Classes”HttpRequest
Section titled “HttpRequest”export class HttpRequest {
readonly method: string;
readonly url: string;
readonly path: string;
readonly query: QueryParams;
readonly headers: Readonly<Record<string, string>>;
readonly params: Readonly<Record<string, string>>;
readonly cookies: Readonly<Record<string, string>>;
readonly remoteAddr: string;
header(name: string): string | undefined;
param(name: string): string | undefined;
bodyBytes(): Uint8Array;
text(): Promise<string>;
json<T = unknown>(): Promise<T>;
form(): Promise<QueryParams>;
}
Immutable incoming HTTP request passed to handlers and middleware.
| Property | Type | Description | Since |
|---|---|---|---|
method readonly | string | Uppercase HTTP request method (for example "GET" or "POST"). | v0.0.0-alpha.0 |
url readonly | string | Raw request URL or path+query string. | v0.0.0-alpha.0 |
path readonly | string | Normalized request pathname without query string. | v0.0.0-alpha.0 |
query readonly | QueryParams | Parsed read-only URL query parameters. | v0.0.0-alpha.0 |
headers readonly | Readonly<Record<string, string>> | Lowercased frozen header map. | v0.0.0-alpha.0 |
params readonly | Readonly<Record<string, string>> | Matched route path parameters (for example { id: "42" }). | v0.0.0-alpha.0 |
cookies readonly | Readonly<Record<string, string>> | Parsed request Cookie header map. | v0.0.0-alpha.0 |
remoteAddr readonly | string | Remote peer address string (for example "127.0.0.1:54321"). | v0.0.0-alpha.0 |
HttpRequest.header
Section titled “HttpRequest.header”header(name: string): string | undefined;
Case-insensitive header lookup.
| Name | Type | Description |
|---|---|---|
name | string | Header field name. |
string | undefined — Header value, or undefined if not present.HttpRequest.param
Section titled “HttpRequest.param”param(name: string): string | undefined;
Route path parameter lookup.
| Name | Type | Description |
|---|---|---|
name | string | Route wildcard parameter name. |
string | undefined — Captured parameter string, or undefined if absent.HttpRequest.bodyBytes
Section titled “HttpRequest.bodyBytes”bodyBytes(): Uint8Array;
Return a fresh copy of the raw request body bytes.
Uint8Array — Fresh Uint8Array copy of the request body.HttpRequest.text
Section titled “HttpRequest.text”text(): Promise<string>;
Decode the request body as strict UTF-8 text.
Promise<string> — Promise resolving to the UTF-8 request body string.HttpError— withstatus = 400on invalid UTF-8 bytes.
HttpRequest.json
Section titled “HttpRequest.json”json<T = unknown>(): Promise<T>;
Decode and parse a JSON request body.
Promise<T> — Promise resolving to the parsed JSON value.HttpError— withstatus = 400on invalid UTF-8 or malformed JSON.
HttpRequest.form
Section titled “HttpRequest.form”form(): Promise<QueryParams>;
Decode an application/x-www-form-urlencoded body into QueryParams.
Promise<QueryParams> — Promise resolving to parsed form parameters.HttpError— withstatus = 400on invalid UTF-8 or malformed form data.
HttpResponse
Section titled “HttpResponse”export class HttpResponse {
readonly status: number;
readonly headers: Readonly<Record<string, string>>;
readonly body: Uint8Array;
header(name: string): string | undefined;
headerValues(name: string): string[];
bytes(): Uint8Array;
text(): string;
json<T = unknown>(): T;
}
Immutable HTTP response descriptor returned by handlers and response builders.
| Property | Type | Description | Since |
|---|---|---|---|
status readonly | number | HTTP status code (100..=599). | v0.0.0-alpha.0 |
headers readonly | Readonly<Record<string, string>> | Lowercased frozen response header map. | v0.0.0-alpha.0 |
body readonly | Uint8Array | Immutable response body bytes. | v0.0.0-alpha.0 |
HttpResponse.header
Section titled “HttpResponse.header”header(name: string): string | undefined;
Case-insensitive lookup for the collapsed header value.
| Name | Type | Description |
|---|---|---|
name | string | Header field name. |
string | undefined — Header value, or undefined if absent.HttpResponse.headerValues
Section titled “HttpResponse.headerValues”headerValues(name: string): string[];
Case-insensitive lookup returning all header values for name (e.g. set-cookie).
| Name | Type | Description |
|---|---|---|
name | string | Header field name. |
string[] — Array of header values in emission order.HttpResponse.bytes
Section titled “HttpResponse.bytes”bytes(): Uint8Array;
Return a fresh copy of the response body bytes.
Uint8Array — Fresh Uint8Array copy of the response body.HttpResponse.text
Section titled “HttpResponse.text”text(): string;
Decode the response body as strict UTF-8 text.
string — UTF-8 decoded response body string.TypeError— if the response body is not valid UTF-8.
HttpResponse.json
Section titled “HttpResponse.json”json<T = unknown>(): T;
Decode and parse the response body as JSON.
T — Parsed JSON value.SyntaxError— if the body is not valid JSON.
HttpError
Section titled “HttpError”export class HttpError extends Error {
override name: "HttpError";
status: number;
code?: string;
details?: unknown;
headers?: Readonly<Record<string, string>>;
constructor(status: number, message?: string, code?: string, details?: unknown);
}
Structured HTTP error converted into an HTTP response by ServeMux and recover().
constructor(status: number, message?: string, code?: string, details?: unknown);
Construct an HttpError.
| Name | Type | Description |
|---|---|---|
status | number | HTTP status code. |
message optional | string | Optional error message. |
code optional | string | Optional machine-readable error code. |
details optional | unknown | Optional structured error details. |
| Property | Type | Description | Since |
|---|---|---|---|
name | "HttpError" | Error name ("HttpError"). | v0.0.0-alpha.0 |
status | number | HTTP status code (400..=599). | v0.0.0-alpha.0 |
code optional | string | Optional machine-readable error code. | v0.0.0-alpha.0 |
details optional | unknown | Optional structured error details. | v0.0.0-alpha.0 |
headers optional | Readonly<Record<string, string>> | Optional extra response headers (for example Allow on 405). | v0.0.0-alpha.0 |
ServeMux
Section titled “ServeMux”export class ServeMux {
constructor();
handle(pattern: string, handler: Handler): ServeMux;
get(path: string, handler: Handler): ServeMux;
post(path: string, handler: Handler): ServeMux;
put(path: string, handler: Handler): ServeMux;
patch(path: string, handler: Handler): ServeMux;
delete(path: string, handler: Handler): ServeMux;
use(...middlewares: Middleware[]): ServeMux;
group(prefix: string, fn: (sub: ServeMux) => void): ServeMux;
static(urlPrefix: string, rootDir: string, options?: StaticOptions): ServeMux;
fetch(input: string | FetchInput, init?: FetchInit): Promise<HttpResponse>;
}
Go 1.22+ ServeMux-style HTTP router with middleware, route groups,
traversal-safe static file serving, and zero-socket .fetch() testing.
constructor();
Create an empty ServeMux router.
ServeMux.handle
Section titled “ServeMux.handle”handle(pattern: string, handler: Handler): ServeMux;
Register a Go 1.22+ pattern ("GET /users/{id}", "/files/{path...}", etc.).
| Name | Type | Description |
|---|---|---|
pattern | string | Route pattern string (optional method prefix + path with {param} or {rest...} wildcards). |
handler | Handler | Route handler function. |
ServeMux — this for chaining.TypeError— whenpatternis invalid or conflicts with an existing route.
ServeMux.get
Section titled “ServeMux.get”get(path: string, handler: Handler): ServeMux;
Register a GET (and automatic HEAD) route.
| Name | Type | Description |
|---|---|---|
path | string | Route path pattern. |
handler | Handler | Route handler function. |
ServeMux — this for chaining.ServeMux.post
Section titled “ServeMux.post”post(path: string, handler: Handler): ServeMux;
Register a POST route.
| Name | Type | Description |
|---|---|---|
path | string | Route path pattern. |
handler | Handler | Route handler function. |
ServeMux — this for chaining.ServeMux.put
Section titled “ServeMux.put”put(path: string, handler: Handler): ServeMux;
Register a PUT route.
| Name | Type | Description |
|---|---|---|
path | string | Route path pattern. |
handler | Handler | Route handler function. |
ServeMux — this for chaining.ServeMux.patch
Section titled “ServeMux.patch”patch(path: string, handler: Handler): ServeMux;
Register a PATCH route.
| Name | Type | Description |
|---|---|---|
path | string | Route path pattern. |
handler | Handler | Route handler function. |
ServeMux — this for chaining.ServeMux.delete
Section titled “ServeMux.delete”delete(path: string, handler: Handler): ServeMux;
Register a DELETE route.
| Name | Type | Description |
|---|---|---|
path | string | Route path pattern. |
handler | Handler | Route handler function. |
ServeMux — this for chaining.ServeMux.use
Section titled “ServeMux.use”use(...middlewares: Middleware[]): ServeMux;
Attach middleware to this router (or current route group).
| Name | Type | Description |
|---|---|---|
...middlewares | Middleware[] | Middleware functions applied in left-to-right order. |
ServeMux — this for chaining.ServeMux.group
Section titled “ServeMux.group”group(prefix: string, fn: (sub: ServeMux) => void): ServeMux;
Mount a prefixed route group with optional group-local .use() middleware.
| Name | Type | Description |
|---|---|---|
prefix | string | Path prefix for all routes registered inside fn. |
fn | (sub: ServeMux) => void | Builder callback receiving the scoped ServeMux group. |
ServeMux — this for chaining.import { createRouter, json } from "vael:http";
const router = createRouter();router.group("/api", (api) => { api.get("/health", () => json({ ok: true }));});ServeMux.static
Section titled “ServeMux.static”static(urlPrefix: string, rootDir: string, options?: StaticOptions): ServeMux;
Serve static files from rootDir under urlPrefix with traversal/symlink protection.
| Name | Type | Description |
|---|---|---|
urlPrefix | string | URL mount prefix (for example "/assets"). |
rootDir | string | Local filesystem directory root. |
options optional | StaticOptions | Optional static serving options ({ index }). |
ServeMux — this for chaining.ServeMux.fetch
Section titled “ServeMux.fetch”fetch(input: string | FetchInput, init?: FetchInit): Promise<HttpResponse>;
Dispatch a direct in-memory request through the router with zero sockets.
| Name | Type | Description |
|---|---|---|
input | string | FetchInput | Request URL string or FetchInput descriptor. |
init optional | FetchInit | Optional request method, headers, body, and remote address overrides. |
Promise<HttpResponse> — Promise resolving to the produced HttpResponse.import { createRouter, text } from "vael:http";
const router = createRouter();router.get("/ping", () => text("pong"));const res = await router.fetch("/ping");console.log(res.status, res.text());Interfaces
Section titled “Interfaces”QueryParams
Section titled “QueryParams”export interface QueryParams {
readonly size: number;
get(name: string): string | null;
getAll(name: string): string[];
has(name: string): boolean;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
entries(): IterableIterator<[string, string]>;
[Symbol.iterator](): IterableIterator<[string, string]>;
forEach(callback: (value: string, key: string, parent: QueryParams) => void): void;
toString(): string;
}
Read-only URL query or application/x-www-form-urlencoded parameter bag.
| Property | Type | Description | Since |
|---|---|---|---|
size readonly | number | Number of parameter entries. | v0.0.0-alpha.0 |
QueryParams.get
Section titled “QueryParams.get”get(name: string): string | null;
Return the first value associated with name, or null if absent.
| Name | Type | Description |
|---|---|---|
name | string | Parameter name. |
string | null — First parameter value, or null.QueryParams.getAll
Section titled “QueryParams.getAll”getAll(name: string): string[];
Return all values associated with name in insertion order.
| Name | Type | Description |
|---|---|---|
name | string | Parameter name. |
string[] — Array of matching parameter values.QueryParams.has
Section titled “QueryParams.has”has(name: string): boolean;
Return true if name is present at least once.
| Name | Type | Description |
|---|---|---|
name | string | Parameter name. |
boolean — true if name exists.QueryParams.keys
Section titled “QueryParams.keys”keys(): IterableIterator<string>;
Iterate parameter names in insertion order.
IterableIterator<string> — Iterator over parameter names.QueryParams.values
Section titled “QueryParams.values”values(): IterableIterator<string>;
Iterate parameter values in insertion order.
IterableIterator<string> — Iterator over parameter values.QueryParams.entries
Section titled “QueryParams.entries”entries(): IterableIterator<[string, string]>;
Iterate [name, value] pairs in insertion order.
IterableIterator<[string, string]> — Iterator over [name, value] entries.QueryParams.[Symbol.iterator]
Section titled “QueryParams.[Symbol.iterator]”[Symbol.iterator](): IterableIterator<[string, string]>;
Default iterator yielding [name, value] pairs in insertion order.
IterableIterator<[string, string]> — Iterator over [name, value] entries.QueryParams.forEach
Section titled “QueryParams.forEach”forEach(callback: (value: string, key: string, parent: QueryParams) => void): void;
Invoke callback once for each [name, value] entry in insertion order.
| Name | Type | Description |
|---|---|---|
callback | (value: string, key: string, parent: QueryParams) => void | Callback receiving (value, key, parent). |
voidQueryParams.toString
Section titled “QueryParams.toString”toString(): string;
Serialize all parameters as a URL-encoded query string.
string — URL-encoded query string without a leading "?".AbortSignalLike
Section titled “AbortSignalLike”export interface AbortSignalLike {
readonly aborted: boolean;
addEventListener(type: "abort", listener: () => void, options?: { once?: boolean }): void;
removeEventListener?(type: "abort", listener: () => void): void;
}
Minimal abort-signal contract accepted by serve({ signal }).
| Property | Type | Description | Since |
|---|---|---|---|
aborted readonly | boolean | Whether the signal has already been aborted. | v0.0.0-alpha.0 |
AbortSignalLike.addEventListener
Section titled “AbortSignalLike.addEventListener”addEventListener(type: "abort", listener: () => void, options?: { once?: boolean }): void;
Register an "abort" listener.
| Name | Type | Description |
|---|---|---|
type | "abort" | Event type ("abort"). |
listener | () => void | Callback invoked upon abort. |
options optional | { once?: boolean } | Optional listener options ({ once }). |
voidAbortSignalLike.removeEventListener
Section titled “AbortSignalLike.removeEventListener”removeEventListener?(type: "abort", listener: () => void): void;
Unregister a previously registered "abort" listener.
| Name | Type | Description |
|---|---|---|
type | "abort" | Event type ("abort"). |
listener | () => void | Listener callback to remove. |
voidResponseInit
Section titled “ResponseInit”export interface ResponseInit {
status?: number;
headers?: HeadersInit;
}
Options accepted by response, json, html, text, and noContent.
| Property | Type | Description | Since |
|---|---|---|---|
status optional | number | HTTP status code (100..=599, default 200). | v0.0.0-alpha.0 |
headers optional | HeadersInit | HTTP response headers, validated against RFC 9110 and CRLF-safe rules. | v0.0.0-alpha.0 |
SetCookieOptions
Section titled “SetCookieOptions”export interface SetCookieOptions {
name: string;
value: string;
path?: string;
domain?: string;
maxAge?: number;
httpOnly?: boolean;
secure?: boolean;
sameSite?: SameSitePolicy;
}
Options accepted by setCookie and formatSetCookie.
| Property | Type | Description | Since |
|---|---|---|---|
name | string | Cookie name (RFC 6265 token, no whitespace or separators). | v0.0.0-alpha.0 |
value | string | Cookie value (CRLF-free). | v0.0.0-alpha.0 |
path optional | string | Optional Path cookie attribute. | v0.0.0-alpha.0 |
domain optional | string | Optional Domain cookie attribute. | v0.0.0-alpha.0 |
maxAge optional | number | Optional Max-Age attribute in whole seconds. | v0.0.0-alpha.0 |
httpOnly optional | boolean | Whether to include the HttpOnly attribute. | v0.0.0-alpha.0 |
secure optional | boolean | Whether to include the Secure attribute. | v0.0.0-alpha.0 |
sameSite optional | SameSitePolicy | Optional SameSite attribute ("Lax", "Strict", or "None"). | v0.0.0-alpha.0 |
RequestContext
Section titled “RequestContext”export interface RequestContext {
readonly params: Readonly<Record<string, string>>;
readonly state: Record<string, unknown>;
readonly remoteAddr: string;
}
Per-request context passed alongside HttpRequest to handlers and middleware.
| Property | Type | Description | Since |
|---|---|---|---|
params readonly | Readonly<Record<string, string>> | Matched route path parameters. | v0.0.0-alpha.0 |
state readonly | Record<string, unknown> | Mutable per-request state bag shared across middleware and handler. | v0.0.0-alpha.0 |
remoteAddr readonly | string | Remote peer address string. | v0.0.0-alpha.0 |
StaticOptions
Section titled “StaticOptions”export interface StaticOptions {
index?: string | null;
}
Options accepted by ServeMux.static(urlPrefix, rootDir, options).
| Property | Type | Description | Since |
|---|---|---|---|
index optional | string | null | Directory index filename (default "index.html", or null to disable directory index). | v0.0.0-alpha.0 |
FetchInput
Section titled “FetchInput”export interface FetchInput {
url: string;
method?: string;
headers?: HeadersInit;
body?: string | Uint8Array | null;
remoteAddr?: string;
}
Request input accepted by ServeMux.fetch(input, init).
| Property | Type | Description | Since |
|---|---|---|---|
url | string | Request URL or path+query string. | v0.0.0-alpha.0 |
method optional | string | HTTP method (default "GET"). | v0.0.0-alpha.0 |
headers optional | HeadersInit | Request headers. | v0.0.0-alpha.0 |
body optional | string | Uint8Array | null | Request body string, bytes, or null. | v0.0.0-alpha.0 |
remoteAddr optional | string | Synthetic remote address string for testing. | v0.0.0-alpha.0 |
FetchInit
Section titled “FetchInit”export interface FetchInit {
method?: string;
headers?: HeadersInit;
body?: string | Uint8Array | null;
remoteAddr?: string;
}
Request init overrides accepted by ServeMux.fetch(input, init).
| Property | Type | Description | Since |
|---|---|---|---|
method optional | string | HTTP method override (default "GET"). | v0.0.0-alpha.0 |
headers optional | HeadersInit | Request headers override. | v0.0.0-alpha.0 |
body optional | string | Uint8Array | null | Request body override. | v0.0.0-alpha.0 |
remoteAddr optional | string | Synthetic remote address override. | v0.0.0-alpha.0 |
RecoverOptions
Section titled “RecoverOptions”export interface RecoverOptions {
onError?: (error: unknown, req: HttpRequest, ctx: RequestContext) => void;
}
Options accepted by recover().
| Property | Type | Description | Since |
|---|---|---|---|
onError optional | (error: unknown, req: HttpRequest, ctx: RequestContext) => void | Optional error observer invoked when a downstream handler throws or rejects. | v0.0.0-alpha.0 |
RequestIdOptions
Section titled “RequestIdOptions”export interface RequestIdOptions {
headerName?: string;
generator?: () => string;
}
Options accepted by requestId().
| Property | Type | Description | Since |
|---|---|---|---|
headerName optional | string | Request/response header name (default "x-request-id"). | v0.0.0-alpha.0 |
generator optional | () => string | Custom ID generator invoked when no valid incoming request ID header is present. | v0.0.0-alpha.0 |
LogEntry
Section titled “LogEntry”export interface LogEntry {
readonly method: string;
readonly path: string;
readonly status: number;
readonly durationMs: number;
readonly requestId: string | undefined;
}
Structured request log record passed to logger({ sink }).
| Property | Type | Description | Since |
|---|---|---|---|
method readonly | string | HTTP method. | v0.0.0-alpha.0 |
path readonly | string | Request pathname. | v0.0.0-alpha.0 |
status readonly | number | Response HTTP status code. | v0.0.0-alpha.0 |
durationMs readonly | number | Request handling duration in milliseconds. | v0.0.0-alpha.0 |
requestId readonly | string | undefined | Request ID from ctx.state.requestId, if set. | v0.0.0-alpha.0 |
LoggerOptions
Section titled “LoggerOptions”export interface LoggerOptions {
sink?: (entry: LogEntry) => void;
}
Options accepted by logger().
| Property | Type | Description | Since |
|---|---|---|---|
sink optional | (entry: LogEntry) => void | Custom sink receiving each LogEntry (defaults to console.log). | v0.0.0-alpha.0 |
SecurityHeadersOptions
Section titled “SecurityHeadersOptions”export interface SecurityHeadersOptions {
contentTypeOptions?: string | false;
frameOptions?: string | false;
referrerPolicy?: string | false;
}
Options accepted by securityHeaders().
| Property | Type | Description | Since |
|---|---|---|---|
contentTypeOptions optional | string | false | X-Content-Type-Options value (default "nosniff", or false to omit). | v0.0.0-alpha.0 |
frameOptions optional | string | false | X-Frame-Options value (default "DENY", or false to omit). | v0.0.0-alpha.0 |
referrerPolicy optional | string | false | Referrer-Policy value (default "no-referrer", or false to omit). | v0.0.0-alpha.0 |
CorsOptions
Section titled “CorsOptions”export interface CorsOptions {
origin?: string | string[] | ((origin: string, req: HttpRequest) => string | boolean | null | undefined);
methods?: string[];
allowHeaders?: string[];
exposeHeaders?: string[];
credentials?: boolean;
maxAge?: number;
}
Options accepted by cors().
| Property | Type | Description | Since |
|---|---|---|---|
origin optional | string | string[] | ((origin: string, req: HttpRequest) => string | boolean | null | undefined) | Allowed origin string, list of origins, or dynamic predicate callback. | v0.0.0-alpha.0 |
methods optional | string[] | Allowed HTTP methods for preflight responses. | v0.0.0-alpha.0 |
allowHeaders optional | string[] | Allowed request headers for preflight responses. | v0.0.0-alpha.0 |
exposeHeaders optional | string[] | Response headers exposed to browser clients. | v0.0.0-alpha.0 |
credentials optional | boolean | Whether to emit Access-Control-Allow-Credentials: true. | v0.0.0-alpha.0 |
maxAge optional | number | Preflight cache duration (Access-Control-Max-Age) in seconds. | v0.0.0-alpha.0 |
ServeOptions
Section titled “ServeOptions”export interface ServeOptions {
host?: string;
port?: number;
maxBodyBytes?: number;
signal?: AbortSignalLike;
}
Options accepted by serve(options, handlerOrMux).
| Property | Type | Description | Since |
|---|---|---|---|
host optional | string | Bind host IP or hostname (default "127.0.0.1"). | v0.0.0-alpha.0 |
port optional | number | Bind port (0..=65535, default 8080; 0 selects an ephemeral OS port). | v0.0.0-alpha.0 |
maxBodyBytes optional | number | Maximum accepted request body size in bytes (default 10 MiB). | v0.0.0-alpha.0 |
signal optional | AbortSignalLike | Optional abort signal that closes the server when aborted. | v0.0.0-alpha.0 |
Server
Section titled “Server”export interface Server {
readonly host: string;
readonly port: number;
readonly addr: string;
readonly url: string;
close(): Promise<void>;
readonly finished: Promise<void>;
[Symbol.asyncDispose](): Promise<void>;
}
Running HTTP/1.1 server handle returned by serve().
| Property | Type | Description | Since |
|---|---|---|---|
host readonly | string | Bound host address string. | v0.0.0-alpha.0 |
port readonly | number | Bound TCP port (resolved ephemeral port when started with port: 0). | v0.0.0-alpha.0 |
addr readonly | string | Bound host:port socket string. | v0.0.0-alpha.0 |
url readonly | string | Base HTTP URL (for example "http://127.0.0.1:8080"). | v0.0.0-alpha.0 |
finished readonly | Promise<void> | Promise that resolves once the server has stopped. | v0.0.0-alpha.0 |
Server.close
Section titled “Server.close”close(): Promise<void>;
Gracefully stop accepting connections and close the HTTP server.
Promise<void> — Promise resolving once shutdown finishes.Server.[Symbol.asyncDispose]
Section titled “Server.[Symbol.asyncDispose]”[Symbol.asyncDispose](): Promise<void>;
Async disposal hook (await using) delegating to close().
Promise<void> — Promise resolving once the server has closed.Type Aliases
Section titled “Type Aliases”HeadersInit
Section titled “HeadersInit”export type HeadersInit = Record<string, string | undefined> | ReadonlyArray<readonly [string, string]>;
HTTP header collection input: either a plain object or ordered [name, value] pairs.
RedirectStatus
Section titled “RedirectStatus”export type RedirectStatus = 301 | 302 | 303 | 307 | 308;
Supported HTTP redirect status codes.
SameSitePolicy
Section titled “SameSitePolicy”export type SameSitePolicy = "Lax" | "Strict" | "None";
Set-Cookie SameSite policy attribute.
Handler
Section titled “Handler”export type Handler = (req: HttpRequest, ctx: RequestContext) => HttpResponse | Promise<HttpResponse>;
Pure HTTP handler returning an HttpResponse (synchronously or as a Promise).
Middleware
Section titled “Middleware”export type Middleware = (next: Handler) => Handler;
Composable middleware wrapping a downstream Handler.
