Skip to content
VaelJS Blog

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"
Since v0.0.0-alpha.0 vjs (V8)
Cargo feature: vael-http (enabled by default in vaeljs-core; absent in vaeljs-lite-core)
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());
API Symbols
Functions (24)
createRoutervjs onlyv0.0.0-alpha.0
Create a new ServeMux router instance.
responsevjs onlyv0.0.0-alpha.0
Create an immutable HttpResponse.
jsonvjs onlyv0.0.0-alpha.0
Create an immutable JSON HttpResponse (content-type: application/json; charset=utf-8).
htmlvjs onlyv0.0.0-alpha.0
Create an immutable HTML HttpResponse (content-type: text/html; charset=utf-8).
textvjs onlyv0.0.0-alpha.0
Create an immutable plain-text HttpResponse (content-type: text/plain; charset=utf-8).
redirectvjs onlyv0.0.0-alpha.0
Create an immutable redirect HttpResponse (default 302).
noContentvjs onlyv0.0.0-alpha.0
Create an immutable 204 No Content HttpResponse.
setCookievjs onlyv0.0.0-alpha.0
Return a new HttpResponse with an RFC 6265 / CRLF-safe Set-Cookie header appended.
httpErrorvjs onlyv0.0.0-alpha.0
Construct an HttpError.
badRequestvjs onlyv0.0.0-alpha.0
Construct a 400 Bad Request HttpError.
unauthorizedvjs onlyv0.0.0-alpha.0
Construct a 401 Unauthorized HttpError.
forbiddenvjs onlyv0.0.0-alpha.0
Construct a 403 Forbidden HttpError.
notFoundvjs onlyv0.0.0-alpha.0
Construct a 404 Not Found HttpError.
conflictvjs onlyv0.0.0-alpha.0
Construct a 409 Conflict HttpError.
methodNotAllowedvjs onlyv0.0.0-alpha.0
Construct a 405 Method Not Allowed HttpError with optional Allow methods.
recovervjs onlyv0.0.0-alpha.0
Middleware that converts HttpError to its response and unexpected throws to 500.
requestIdvjs onlyv0.0.0-alpha.0
Middleware that propagates or generates a safe x-request-id on ctx.state.requestId and the response.
loggervjs onlyv0.0.0-alpha.0
Middleware that logs request method, path, status, and duration.
securityHeadersvjs onlyv0.0.0-alpha.0
Middleware that attaches x-content-type-options, x-frame-options, and referrer-policy defaults.
corsvjs onlyv0.0.0-alpha.0
Middleware that handles CORS preflight requests and Access-Control-* response headers.
composevjs onlyv0.0.0-alpha.0
Compose middleware functions left-to-right into a single Middleware.
servevjs onlyv0.0.0-alpha.0
Start a live HTTP/1.1 server backed by hyper and tokio::net::TcpListener.
parseCookiesvjs onlyv0.0.0-alpha.0
Parse an HTTP Cookie request header into { name: value } pairs.
formatSetCookievjs onlyv0.0.0-alpha.0
Format and validate an RFC 6265 / CRLF-safe Set-Cookie header value.
functionSince v0.0.0-alpha.0vjs only
export function createRouter(): ServeMux;

Create a new ServeMux router instance.

Returns
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());
functionSince v0.0.0-alpha.0vjs only
export function response(body?: string | Uint8Array | null, init?: ResponseInit): HttpResponse;

Create an immutable HttpResponse.

Parameters
NameTypeDescription
body optionalstring | Uint8Array | nullOptional response body string, bytes, or null.
init optionalResponseInitOptional status code and headers.
Returns
HttpResponse — Immutable HttpResponse.
Exceptions
  • TypeError — on invalid status code or unsafe header values.
functionSince v0.0.0-alpha.0vjs only
export function json(data: unknown, init?: ResponseInit): HttpResponse;

Create an immutable JSON HttpResponse (content-type: application/json; charset=utf-8).

Parameters
NameTypeDescription
dataunknownJSON-serializable value.
init optionalResponseInitOptional status code and headers.
Returns
HttpResponse — Immutable JSON HttpResponse.
import { json } from "vael:http";
const res = json({ ok: true }, { status: 201 });
console.log(res.status, res.text());
functionSince v0.0.0-alpha.0vjs only
export function html(body: string, init?: ResponseInit): HttpResponse;

Create an immutable HTML HttpResponse (content-type: text/html; charset=utf-8).

Parameters
NameTypeDescription
bodystringHTML body string.
init optionalResponseInitOptional status code and headers.
Returns
HttpResponse — Immutable HTML HttpResponse.
functionSince v0.0.0-alpha.0vjs only
export function text(body: string, init?: ResponseInit): HttpResponse;

Create an immutable plain-text HttpResponse (content-type: text/plain; charset=utf-8).

Parameters
NameTypeDescription
bodystringPlain-text body string.
init optionalResponseInitOptional status code and headers.
Returns
HttpResponse — Immutable plain-text HttpResponse.
functionSince v0.0.0-alpha.0vjs only
export function redirect(location: string, status?: RedirectStatus): HttpResponse;

Create an immutable redirect HttpResponse (default 302).

Parameters
NameTypeDescription
locationstringTarget Location header URL or path (CRLF-free).
status optionalRedirectStatusRedirect status code (301, 302, 303, 307, or 308, default 302).
Returns
HttpResponse — Immutable redirect HttpResponse.
Exceptions
  • TypeError — on invalid status code or unsafe location.
functionSince v0.0.0-alpha.0vjs only
export function noContent(init?: ResponseInit): HttpResponse;

Create an immutable 204 No Content HttpResponse.

Parameters
NameTypeDescription
init optionalResponseInitOptional status/headers overrides (defaults to status 204).
Returns
HttpResponse — Immutable empty HttpResponse.
functionSince v0.0.0-alpha.0vjs only
export function setCookie(res: HttpResponse, cookie: SetCookieOptions): HttpResponse;

Return a new HttpResponse with an RFC 6265 / CRLF-safe Set-Cookie header appended.

Parameters
NameTypeDescription
resHttpResponseBase immutable HttpResponse.
cookieSetCookieOptionsCookie name, value, and attributes.
Returns
HttpResponse — New HttpResponse with the Set-Cookie header appended.
Exceptions
  • TypeError — when cookie name, value, or attributes fail validation.
functionSince v0.0.0-alpha.0vjs only
export function httpError(status: number, message?: string, code?: string, details?: unknown): HttpError;

Construct an HttpError.

Parameters
NameTypeDescription
statusnumberHTTP status code (400..=599).
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
details optionalunknownOptional structured error details.
Returns
HttpError — New HttpError instance.
functionSince v0.0.0-alpha.0vjs only
export function badRequest(message?: string, code?: string): HttpError;

Construct a 400 Bad Request HttpError.

Parameters
NameTypeDescription
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
Returns
HttpError — HttpError with status = 400.
functionSince v0.0.0-alpha.0vjs only
export function unauthorized(message?: string, code?: string): HttpError;

Construct a 401 Unauthorized HttpError.

Parameters
NameTypeDescription
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
Returns
HttpError — HttpError with status = 401.
functionSince v0.0.0-alpha.0vjs only
export function forbidden(message?: string, code?: string): HttpError;

Construct a 403 Forbidden HttpError.

Parameters
NameTypeDescription
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
Returns
HttpError — HttpError with status = 403.
functionSince v0.0.0-alpha.0vjs only
export function notFound(message?: string, code?: string): HttpError;

Construct a 404 Not Found HttpError.

Parameters
NameTypeDescription
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
Returns
HttpError — HttpError with status = 404.
functionSince v0.0.0-alpha.0vjs only
export function conflict(message?: string, code?: string): HttpError;

Construct a 409 Conflict HttpError.

Parameters
NameTypeDescription
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
Returns
HttpError — HttpError with status = 409.
functionSince v0.0.0-alpha.0vjs only
export function methodNotAllowed(allow?: string[], message?: string): HttpError;

Construct a 405 Method Not Allowed HttpError with optional Allow methods.

Parameters
NameTypeDescription
allow optionalstring[]Optional list of allowed HTTP methods for the Allow header.
message optionalstringOptional error message.
Returns
HttpError — HttpError with status = 405.
functionSince v0.0.0-alpha.0vjs only
export function recover(options?: RecoverOptions): Middleware;

Middleware that converts HttpError to its response and unexpected throws to 500.

Parameters
NameTypeDescription
options optionalRecoverOptionsOptional { onError } observer.
Returns
Middleware — Composable Middleware function.
functionSince v0.0.0-alpha.0vjs only
export function requestId(options?: RequestIdOptions): Middleware;

Middleware that propagates or generates a safe x-request-id on ctx.state.requestId and the response.

Parameters
NameTypeDescription
options optionalRequestIdOptionsOptional { headerName, generator } configuration.
Returns
Middleware — Composable Middleware function.
functionSince v0.0.0-alpha.0vjs only
export function logger(options?: LoggerOptions): Middleware;

Middleware that logs request method, path, status, and duration.

Parameters
NameTypeDescription
options optionalLoggerOptionsOptional { sink } configuration.
Returns
Middleware — Composable Middleware function.
functionSince v0.0.0-alpha.0vjs only
export function securityHeaders(options?: SecurityHeadersOptions): Middleware;

Middleware that attaches x-content-type-options, x-frame-options, and referrer-policy defaults.

Parameters
NameTypeDescription
options optionalSecurityHeadersOptionsOptional header overrides or false flags to disable individual headers.
Returns
Middleware — Composable Middleware function.
functionSince v0.0.0-alpha.0vjs only
export function cors(options?: CorsOptions): Middleware;

Middleware that handles CORS preflight requests and Access-Control-* response headers.

Parameters
NameTypeDescription
options optionalCorsOptionsOptional CORS policy configuration.
Returns
Middleware — Composable Middleware function.
functionSince v0.0.0-alpha.0vjs only
export function compose(...middlewares: Middleware[]): Middleware;

Compose middleware functions left-to-right into a single Middleware.

Parameters
NameTypeDescription
...middlewaresMiddleware[]Middleware functions to compose.
Returns
Middleware — Combined Middleware function.
functionSince v0.0.0-alpha.0vjs only
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.

Overload 1 — serve(handlerOrMux)
NameTypeDescription
handlerOrMuxHandler | ServeMuxRequest handler function or ServeMux router instance.
Server — Running Server handle.
Overload 2 — serve(options, handlerOrMux)

Start a live HTTP/1.1 server backed by hyper and tokio::net::TcpListener with explicit options.

NameTypeDescription
optionsServeOptionsServer bind host, port, body limit, and optional abort signal.
handlerOrMuxHandler | ServeMuxRequest handler function or ServeMux router instance.
Server — Running Server handle.
Exceptions
  • TypeError — on invalid handler/router; on invalid options or handler/router.
  • Error — on bind failure.
  • RangeError — when port or maxBodyBytes is 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();
functionSince v0.0.0-alpha.0vjs only
export function parseCookies(header: string): Record<string, string>;

Parse an HTTP Cookie request header into { name: value } pairs.

Parameters
NameTypeDescription
headerstringRaw Cookie header value.
Returns
Record<string, string> — Record mapping cookie names to decoded string values.
functionSince v0.0.0-alpha.0vjs only
export function formatSetCookie(options: SetCookieOptions): string;

Format and validate an RFC 6265 / CRLF-safe Set-Cookie header value.

Parameters
NameTypeDescription
optionsSetCookieOptionsCookie name, value, and attributes.
Returns
string — Formatted Set-Cookie header string.
Exceptions
  • TypeError — when cookie name, value, or attributes fail validation.
classSince v0.0.0-alpha.0vjs only
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.

Properties
PropertyTypeDescriptionSince
method readonlystringUppercase HTTP request method (for example "GET" or "POST").v0.0.0-alpha.0
url readonlystringRaw request URL or path+query string.v0.0.0-alpha.0
path readonlystringNormalized request pathname without query string.v0.0.0-alpha.0
query readonlyQueryParamsParsed read-only URL query parameters.v0.0.0-alpha.0
headers readonlyReadonly<Record<string, string>>Lowercased frozen header map.v0.0.0-alpha.0
params readonlyReadonly<Record<string, string>>Matched route path parameters (for example { id: "42" }).v0.0.0-alpha.0
cookies readonlyReadonly<Record<string, string>>Parsed request Cookie header map.v0.0.0-alpha.0
remoteAddr readonlystringRemote peer address string (for example "127.0.0.1:54321").v0.0.0-alpha.0
Methods
methodSince v0.0.0-alpha.0
header(name: string): string | undefined;

Case-insensitive header lookup.

Parameters
NameTypeDescription
namestringHeader field name.
Returns
string | undefined — Header value, or undefined if not present.
methodSince v0.0.0-alpha.0
param(name: string): string | undefined;

Route path parameter lookup.

Parameters
NameTypeDescription
namestringRoute wildcard parameter name.
Returns
string | undefined — Captured parameter string, or undefined if absent.
methodSince v0.0.0-alpha.0
bodyBytes(): Uint8Array;

Return a fresh copy of the raw request body bytes.

Returns
Uint8Array — Fresh Uint8Array copy of the request body.
methodSince v0.0.0-alpha.0
text(): Promise<string>;

Decode the request body as strict UTF-8 text.

Returns
Promise<string> — Promise resolving to the UTF-8 request body string.
Exceptions
  • HttpError — with status = 400 on invalid UTF-8 bytes.
methodSince v0.0.0-alpha.0
json<T = unknown>(): Promise<T>;

Decode and parse a JSON request body.

Returns
Promise<T> — Promise resolving to the parsed JSON value.
Exceptions
  • HttpError — with status = 400 on invalid UTF-8 or malformed JSON.
methodSince v0.0.0-alpha.0
form(): Promise<QueryParams>;

Decode an application/x-www-form-urlencoded body into QueryParams.

Returns
Promise<QueryParams> — Promise resolving to parsed form parameters.
Exceptions
  • HttpError — with status = 400 on invalid UTF-8 or malformed form data.
classSince v0.0.0-alpha.0vjs only
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.

Properties
PropertyTypeDescriptionSince
status readonlynumberHTTP status code (100..=599).v0.0.0-alpha.0
headers readonlyReadonly<Record<string, string>>Lowercased frozen response header map.v0.0.0-alpha.0
body readonlyUint8ArrayImmutable response body bytes.v0.0.0-alpha.0
Methods
methodSince v0.0.0-alpha.0
header(name: string): string | undefined;

Case-insensitive lookup for the collapsed header value.

Parameters
NameTypeDescription
namestringHeader field name.
Returns
string | undefined — Header value, or undefined if absent.
methodSince v0.0.0-alpha.0
headerValues(name: string): string[];

Case-insensitive lookup returning all header values for name (e.g. set-cookie).

Parameters
NameTypeDescription
namestringHeader field name.
Returns
string[] — Array of header values in emission order.
methodSince v0.0.0-alpha.0
bytes(): Uint8Array;

Return a fresh copy of the response body bytes.

Returns
Uint8Array — Fresh Uint8Array copy of the response body.
methodSince v0.0.0-alpha.0
text(): string;

Decode the response body as strict UTF-8 text.

Returns
string — UTF-8 decoded response body string.
Exceptions
  • TypeError — if the response body is not valid UTF-8.
methodSince v0.0.0-alpha.0
json<T = unknown>(): T;

Decode and parse the response body as JSON.

Returns
T — Parsed JSON value.
Exceptions
  • SyntaxError — if the body is not valid JSON.
classSince v0.0.0-alpha.0vjs only
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
constructor(status: number, message?: string, code?: string, details?: unknown);

Construct an HttpError.

Parameters
NameTypeDescription
statusnumberHTTP status code.
message optionalstringOptional error message.
code optionalstringOptional machine-readable error code.
details optionalunknownOptional structured error details.
Properties
PropertyTypeDescriptionSince
name "HttpError"Error name ("HttpError").v0.0.0-alpha.0
status numberHTTP status code (400..=599).v0.0.0-alpha.0
code optionalstringOptional machine-readable error code.v0.0.0-alpha.0
details optionalunknownOptional structured error details.v0.0.0-alpha.0
headers optionalReadonly<Record<string, string>>Optional extra response headers (for example Allow on 405).v0.0.0-alpha.0
classSince v0.0.0-alpha.0vjs only
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
constructor();

Create an empty ServeMux router.

Methods
methodSince v0.0.0-alpha.0
handle(pattern: string, handler: Handler): ServeMux;

Register a Go 1.22+ pattern ("GET /users/{id}", "/files/{path...}", etc.).

Parameters
NameTypeDescription
patternstringRoute pattern string (optional method prefix + path with {param} or {rest...} wildcards).
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
Exceptions
  • TypeError — when pattern is invalid or conflicts with an existing route.
methodSince v0.0.0-alpha.0
get(path: string, handler: Handler): ServeMux;

Register a GET (and automatic HEAD) route.

Parameters
NameTypeDescription
pathstringRoute path pattern.
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
post(path: string, handler: Handler): ServeMux;

Register a POST route.

Parameters
NameTypeDescription
pathstringRoute path pattern.
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
put(path: string, handler: Handler): ServeMux;

Register a PUT route.

Parameters
NameTypeDescription
pathstringRoute path pattern.
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
patch(path: string, handler: Handler): ServeMux;

Register a PATCH route.

Parameters
NameTypeDescription
pathstringRoute path pattern.
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
delete(path: string, handler: Handler): ServeMux;

Register a DELETE route.

Parameters
NameTypeDescription
pathstringRoute path pattern.
handlerHandlerRoute handler function.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
use(...middlewares: Middleware[]): ServeMux;

Attach middleware to this router (or current route group).

Parameters
NameTypeDescription
...middlewaresMiddleware[]Middleware functions applied in left-to-right order.
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
group(prefix: string, fn: (sub: ServeMux) => void): ServeMux;

Mount a prefixed route group with optional group-local .use() middleware.

Parameters
NameTypeDescription
prefixstringPath prefix for all routes registered inside fn.
fn(sub: ServeMux) => voidBuilder callback receiving the scoped ServeMux group.
Returns
ServeMux — this for chaining.
import { createRouter, json } from "vael:http";
const router = createRouter();
router.group("/api", (api) => {
api.get("/health", () => json({ ok: true }));
});
methodSince v0.0.0-alpha.0
static(urlPrefix: string, rootDir: string, options?: StaticOptions): ServeMux;

Serve static files from rootDir under urlPrefix with traversal/symlink protection.

Parameters
NameTypeDescription
urlPrefixstringURL mount prefix (for example "/assets").
rootDirstringLocal filesystem directory root.
options optionalStaticOptionsOptional static serving options ({ index }).
Returns
ServeMux — this for chaining.
methodSince v0.0.0-alpha.0
fetch(input: string | FetchInput, init?: FetchInit): Promise<HttpResponse>;

Dispatch a direct in-memory request through the router with zero sockets.

Parameters
NameTypeDescription
inputstring | FetchInputRequest URL string or FetchInput descriptor.
init optionalFetchInitOptional request method, headers, body, and remote address overrides.
Returns
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());
interfaceSince v0.0.0-alpha.0vjs only
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.

Properties
PropertyTypeDescriptionSince
size readonlynumberNumber of parameter entries.v0.0.0-alpha.0
Methods
methodSince v0.0.0-alpha.0
get(name: string): string | null;

Return the first value associated with name, or null if absent.

Parameters
NameTypeDescription
namestringParameter name.
Returns
string | null — First parameter value, or null.
methodSince v0.0.0-alpha.0
getAll(name: string): string[];

Return all values associated with name in insertion order.

Parameters
NameTypeDescription
namestringParameter name.
Returns
string[] — Array of matching parameter values.
methodSince v0.0.0-alpha.0
has(name: string): boolean;

Return true if name is present at least once.

Parameters
NameTypeDescription
namestringParameter name.
Returns
boolean — true if name exists.
methodSince v0.0.0-alpha.0
keys(): IterableIterator<string>;

Iterate parameter names in insertion order.

Returns
IterableIterator<string> — Iterator over parameter names.
methodSince v0.0.0-alpha.0
values(): IterableIterator<string>;

Iterate parameter values in insertion order.

Returns
IterableIterator<string> — Iterator over parameter values.
methodSince v0.0.0-alpha.0
entries(): IterableIterator<[string, string]>;

Iterate [name, value] pairs in insertion order.

Returns
IterableIterator<[string, string]> — Iterator over [name, value] entries.
methodSince v0.0.0-alpha.0
[Symbol.iterator](): IterableIterator<[string, string]>;

Default iterator yielding [name, value] pairs in insertion order.

Returns
IterableIterator<[string, string]> — Iterator over [name, value] entries.
methodSince v0.0.0-alpha.0
forEach(callback: (value: string, key: string, parent: QueryParams) => void): void;

Invoke callback once for each [name, value] entry in insertion order.

Parameters
NameTypeDescription
callback(value: string, key: string, parent: QueryParams) => voidCallback receiving (value, key, parent).
Returns
void
methodSince v0.0.0-alpha.0
toString(): string;

Serialize all parameters as a URL-encoded query string.

Returns
string — URL-encoded query string without a leading "?".
interfaceSince v0.0.0-alpha.0vjs only
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 }).

Properties
PropertyTypeDescriptionSince
aborted readonlybooleanWhether the signal has already been aborted.v0.0.0-alpha.0
Methods
methodSince v0.0.0-alpha.0
addEventListener(type: "abort", listener: () => void, options?: { once?: boolean }): void;

Register an "abort" listener.

Parameters
NameTypeDescription
type"abort"Event type ("abort").
listener() => voidCallback invoked upon abort.
options optional{ once?: boolean }Optional listener options ({ once }).
Returns
void
methodSince v0.0.0-alpha.0
removeEventListener?(type: "abort", listener: () => void): void;

Unregister a previously registered "abort" listener.

Parameters
NameTypeDescription
type"abort"Event type ("abort").
listener() => voidListener callback to remove.
Returns
void
interfaceSince v0.0.0-alpha.0vjs only
export interface ResponseInit {
  status?: number;
  headers?: HeadersInit;
}

Options accepted by response, json, html, text, and noContent.

Properties
PropertyTypeDescriptionSince
status optionalnumberHTTP status code (100..=599, default 200).v0.0.0-alpha.0
headers optionalHeadersInitHTTP response headers, validated against RFC 9110 and CRLF-safe rules.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
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.

Properties
PropertyTypeDescriptionSince
name stringCookie name (RFC 6265 token, no whitespace or separators).v0.0.0-alpha.0
value stringCookie value (CRLF-free).v0.0.0-alpha.0
path optionalstringOptional Path cookie attribute.v0.0.0-alpha.0
domain optionalstringOptional Domain cookie attribute.v0.0.0-alpha.0
maxAge optionalnumberOptional Max-Age attribute in whole seconds.v0.0.0-alpha.0
httpOnly optionalbooleanWhether to include the HttpOnly attribute.v0.0.0-alpha.0
secure optionalbooleanWhether to include the Secure attribute.v0.0.0-alpha.0
sameSite optionalSameSitePolicyOptional SameSite attribute ("Lax", "Strict", or "None").v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
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.

Properties
PropertyTypeDescriptionSince
params readonlyReadonly<Record<string, string>>Matched route path parameters.v0.0.0-alpha.0
state readonlyRecord<string, unknown>Mutable per-request state bag shared across middleware and handler.v0.0.0-alpha.0
remoteAddr readonlystringRemote peer address string.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface StaticOptions {
  index?: string | null;
}

Options accepted by ServeMux.static(urlPrefix, rootDir, options).

Properties
PropertyTypeDescriptionSince
index optionalstring | nullDirectory index filename (default "index.html", or null to disable directory index).v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface FetchInput {
  url: string;
  method?: string;
  headers?: HeadersInit;
  body?: string | Uint8Array | null;
  remoteAddr?: string;
}

Request input accepted by ServeMux.fetch(input, init).

Properties
PropertyTypeDescriptionSince
url stringRequest URL or path+query string.v0.0.0-alpha.0
method optionalstringHTTP method (default "GET").v0.0.0-alpha.0
headers optionalHeadersInitRequest headers.v0.0.0-alpha.0
body optionalstring | Uint8Array | nullRequest body string, bytes, or null.v0.0.0-alpha.0
remoteAddr optionalstringSynthetic remote address string for testing.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface FetchInit {
  method?: string;
  headers?: HeadersInit;
  body?: string | Uint8Array | null;
  remoteAddr?: string;
}

Request init overrides accepted by ServeMux.fetch(input, init).

Properties
PropertyTypeDescriptionSince
method optionalstringHTTP method override (default "GET").v0.0.0-alpha.0
headers optionalHeadersInitRequest headers override.v0.0.0-alpha.0
body optionalstring | Uint8Array | nullRequest body override.v0.0.0-alpha.0
remoteAddr optionalstringSynthetic remote address override.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface RecoverOptions {
  onError?: (error: unknown, req: HttpRequest, ctx: RequestContext) => void;
}

Options accepted by recover().

Properties
PropertyTypeDescriptionSince
onError optional(error: unknown, req: HttpRequest, ctx: RequestContext) => voidOptional error observer invoked when a downstream handler throws or rejects.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface RequestIdOptions {
  headerName?: string;
  generator?: () => string;
}

Options accepted by requestId().

Properties
PropertyTypeDescriptionSince
headerName optionalstringRequest/response header name (default "x-request-id").v0.0.0-alpha.0
generator optional() => stringCustom ID generator invoked when no valid incoming request ID header is present.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
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 }).

Properties
PropertyTypeDescriptionSince
method readonlystringHTTP method.v0.0.0-alpha.0
path readonlystringRequest pathname.v0.0.0-alpha.0
status readonlynumberResponse HTTP status code.v0.0.0-alpha.0
durationMs readonlynumberRequest handling duration in milliseconds.v0.0.0-alpha.0
requestId readonlystring | undefinedRequest ID from ctx.state.requestId, if set.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface LoggerOptions {
  sink?: (entry: LogEntry) => void;
}

Options accepted by logger().

Properties
PropertyTypeDescriptionSince
sink optional(entry: LogEntry) => voidCustom sink receiving each LogEntry (defaults to console.log).v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface SecurityHeadersOptions {
  contentTypeOptions?: string | false;
  frameOptions?: string | false;
  referrerPolicy?: string | false;
}

Options accepted by securityHeaders().

Properties
PropertyTypeDescriptionSince
contentTypeOptions optionalstring | falseX-Content-Type-Options value (default "nosniff", or false to omit).v0.0.0-alpha.0
frameOptions optionalstring | falseX-Frame-Options value (default "DENY", or false to omit).v0.0.0-alpha.0
referrerPolicy optionalstring | falseReferrer-Policy value (default "no-referrer", or false to omit).v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
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().

Properties
PropertyTypeDescriptionSince
origin optionalstring | 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 optionalstring[]Allowed HTTP methods for preflight responses.v0.0.0-alpha.0
allowHeaders optionalstring[]Allowed request headers for preflight responses.v0.0.0-alpha.0
exposeHeaders optionalstring[]Response headers exposed to browser clients.v0.0.0-alpha.0
credentials optionalbooleanWhether to emit Access-Control-Allow-Credentials: true.v0.0.0-alpha.0
maxAge optionalnumberPreflight cache duration (Access-Control-Max-Age) in seconds.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
export interface ServeOptions {
  host?: string;
  port?: number;
  maxBodyBytes?: number;
  signal?: AbortSignalLike;
}

Options accepted by serve(options, handlerOrMux).

Properties
PropertyTypeDescriptionSince
host optionalstringBind host IP or hostname (default "127.0.0.1").v0.0.0-alpha.0
port optionalnumberBind port (0..=65535, default 8080; 0 selects an ephemeral OS port).v0.0.0-alpha.0
maxBodyBytes optionalnumberMaximum accepted request body size in bytes (default 10 MiB).v0.0.0-alpha.0
signal optionalAbortSignalLikeOptional abort signal that closes the server when aborted.v0.0.0-alpha.0
interfaceSince v0.0.0-alpha.0vjs only
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().

Properties
PropertyTypeDescriptionSince
host readonlystringBound host address string.v0.0.0-alpha.0
port readonlynumberBound TCP port (resolved ephemeral port when started with port: 0).v0.0.0-alpha.0
addr readonlystringBound host:port socket string.v0.0.0-alpha.0
url readonlystringBase HTTP URL (for example "http://127.0.0.1:8080").v0.0.0-alpha.0
finished readonlyPromise<void>Promise that resolves once the server has stopped.v0.0.0-alpha.0
Methods
methodSince v0.0.0-alpha.0
close(): Promise<void>;

Gracefully stop accepting connections and close the HTTP server.

Returns
Promise<void> — Promise resolving once shutdown finishes.
methodSince v0.0.0-alpha.0
[Symbol.asyncDispose](): Promise<void>;

Async disposal hook (await using) delegating to close().

Returns
Promise<void> — Promise resolving once the server has closed.
typeSince v0.0.0-alpha.0vjs only
export type HeadersInit = Record<string, string | undefined> | ReadonlyArray<readonly [string, string]>;

HTTP header collection input: either a plain object or ordered [name, value] pairs.

typeSince v0.0.0-alpha.0vjs only
export type RedirectStatus = 301 | 302 | 303 | 307 | 308;

Supported HTTP redirect status codes.

typeSince v0.0.0-alpha.0vjs only
export type SameSitePolicy = "Lax" | "Strict" | "None";

Set-Cookie SameSite policy attribute.

typeSince v0.0.0-alpha.0vjs only
export type Handler = (req: HttpRequest, ctx: RequestContext) => HttpResponse | Promise<HttpResponse>;

Pure HTTP handler returning an HttpResponse (synchronously or as a Promise).

typeSince v0.0.0-alpha.0vjs only
export type Middleware = (next: Handler) => Handler;

Composable middleware wrapping a downstream Handler.