tyrus:http
tyrus:http is the native HTTP surface for server and route handling. It is designed for API projects generated by choosing the API target in the tyrus new prompts and for explicit services that need typed request and response helpers.
Imports
import { connectWebSocket, CookieOptions, CorsOptions, CsrfOptions, createRouter, fetch, FetchOptions, FetchPolicyOptions, HttpAccessLog, HttpCacheOptions, HttpClientResponse, HttpClientStreamResponse, HttpCookie, HttpError, HttpHeader, HttpReply, HttpReplyOptions, HttpRequest, HttpResponse, HttpRouter, HttpServer, HttpStatus, ServerOptions, StreamBody, WebSocket, WebSocketMessage } from "tyrus:http";Exported Items
| Item | Signature | Purpose |
|---|---|---|
createRouter | () => HttpRouter | Creates a native HTTP router. |
| API Flow | Complete User API example | Follows the main, Model, schemas, routes, controllers, services, and repository in one SQLite-backed flow. |
OpenAPI / Swagger | app.docs(options) | Generates the OpenAPI document and serves the Swagger UI. |
| Automatic route registration | Discovers route modules in src/routes/ without a manual registry. | |
listen | app.listen(port, options?) | Starts the server and returns Result<HttpServer, HttpError>. The runtime keeps it alive after main returns. |
HttpStatus | enum HttpStatus | Named HTTP status codes. |
HttpReply | type HttpReply<T> | Typed reply API for controllers. |
StreamBody | type StreamBody | Opt-in bounded byte stream for a route body or response. |
HttpRouter | type HttpRouter | Native router returned by createRouter. |
onResponse | (hook: (access: HttpAccessLog) => void) => void | Registers an opt-in server-wide response observer. |
HttpAccessLog | interface HttpAccessLog | Immutable metadata for one completed response. |
HttpRequest | interface HttpRequest | Raw request available to pre-handlers and raw routes. |
HttpResponse | interface HttpResponse | Raw response used by pre-handlers and raw routes. |
HttpCacheOptions | interface HttpCacheOptions | ETag configuration passed through HttpReplyOptions. |
HttpReplyOptions | interface HttpReplyOptions | Optional response metadata passed as the second reply.send argument. |
CorsOptions | interface CorsOptions | Complete configuration passed to app.cors(...). |
CsrfOptions | interface CsrfOptions | Double-submit cookie and header names passed to app.csrf(...). |
CookieOptions | interface CookieOptions | Optional attributes passed to reply.setCookie(...). |
HttpCookie | interface HttpCookie | One cookie of reply.setCookies([...]): name, value, and optional options. |
ServerOptions | interface ServerOptions | Host, limits, lifecycle settings, optional access logging, and TLS passed to app.listen(...). |
HttpError | interface HttpError | Recoverable startup failure returned by app.listen(...), with a stable code and a readable message. |
HttpServer | type HttpServer | Running server returned by app.listen(...), with port() and close(). |
WebSocket | type WebSocket | An open WebSocket connection, with stream(), receive(), sendText(text), sendBytes(data), close(), protocol() and closeCode(). |
WebSocketMessage | interface WebSocketMessage | One whole WebSocket message: binary, and its text or its bytes. |
connectWebSocket | (url: string, protocols?: string[]) => Promise<Result<WebSocket, HttpError>> | Opens a WebSocket connection to a ws:// or wss:// URL. |
fetch | (url: string, options?: FetchOptions) => Promise<Result<HttpClientResponse, HttpError>> | Sends one request and reads the answer. |
HttpClientResponse | type HttpClientResponse | The answer a fetch got, with status(), ok(), header(name), text(), bytes(), json<T>() and close(). |
HttpClientStreamResponse | type HttpClientStreamResponse | The head of a fetch.stream(...) response, with stream() for its progressive body. |
FetchOptions | interface FetchOptions | Headers, text or streamed body, timeout, body limit, redirect count and response decompression for a fetch. |
FetchPolicyOptions | interface FetchPolicyOptions | Where fetch may go, passed to app.fetchPolicy(...). |
HttpHeader | interface HttpHeader | One request header, written as { name, value }. |
fetch is the client. It sends one request and reads the answer, and a status is not a failure: 404 and 500 arrive as an ordinary response with ok false, because the request reached a server and got an answer. A transport failure returns Err(HttpError) whose code says which: ERR_HTTP_FETCH_DNS when the name does not resolve, ERR_HTTP_FETCH_CONNECT when the host refuses, ERR_HTTP_FETCH_TLS when the handshake fails, ERR_HTTP_FETCH_TIMEOUT, ERR_HTTP_FETCH_REDIRECT, ERR_HTTP_FETCH_BODY_TOO_LARGE and ERR_HTTP_FETCH_URL. The first three are separate because they call for different things: a name that does not resolve is usually a typo or a stale configuration, a refused connection is often transient and worth retrying, and a handshake that fails will not be fixed by retrying. Connections are reused across requests to one host. The body is read into memory when the request finishes, bounded by maxBodySize (8 MB by default), so text() and bytes() are two views of one body rather than two copies of it; streaming is a separate contract. json<T>() reads that body through the decoder a T.fromJson(text) uses, so a response and a string carrying the same document cannot disagree about what it says, nor about which field is wrong when it is: the failure is the same Result<T, JsonError>, with the same code and the same path. The options are written at the call, because timeout and maxBodySize are read during compilation, the same rule the server options follow.
fetch decodes compressed responses on its own. Unless the program sets accept-encoding itself, each request offers gzip, deflate, br, and a response body in one of those codings arrives decoded, from fetch(...) and from fetch.stream(...) alike, without its content-encoding and content-length headers, which describe the bytes on the wire. maxBodySize bounds the decoded body, a body that expands more than 200 times its compressed size past the first 1 MiB is refused with ERR_HTTP_FETCH_RATIO_LIMIT, and a body that does not match its Content-Encoding is refused with ERR_HTTP_FETCH_DECODE. Pass decompress: false to receive the bytes exactly as the server sent them, for example to store them compressed or to decode them with tyrus:compress under limits of your own.
Use fetch.stream(url, options?) when the body must be read progressively. It returns Ok(HttpClientStreamResponse) after the response head arrives or Err(HttpError) if the request fails before then, and await response.stream() returns its bounded ReadableStream<u8[]>; the regular fetch(...) contract remains buffered.
Use bodyStream to send a progressive request body. It is separate from textual body, so the transfer is visible at the call site; the transport pulls each chunk only when it can accept it, carrying backpressure to the source. fetch(...) and every verb return Promise<Result<HttpClientResponse, HttpError>>.
A streamed request body is one-shot and cannot be replayed. If fetch.stream(...) or FetchOptions.bodyStream receives a redirect, the client preserves the 3xx response and does not issue a second request; inspect its status() and header("location") if the program wants to decide what to do next.
import { fetch, HttpClientResponse, HttpError } from "tyrus:http";
import { FsError, readFileStream } from "tyrus:fs";
import { ReadableStream } from "tyrus:stream";
async function upload(url: string): Promise<void> {
try {
const source: ReadableStream<u8[]> = readFileStream("media/recording-source.bin");
const result = await fetch.post(url, { bodyStream: source });
const response: HttpClientResponse = match result {
Ok(value) => value,
Err(error) => { console.error(error.code); return; }
};
response.close();
} catch (error: FsError) {
console.error(error.code);
} catch (error: HttpError) {
console.error(error.code);
}
}The verbs hang off fetch itself: fetch.get(url), fetch.post(url, options), and the same for put, patch, delete, head, options, connect, query and trace. They are not exported on their own, because import { get, post } would put those names in the scope of every file that wanted one, and get is a name a program has its own uses for. The verb is the only way to name a method: FetchOptions has no method field, so a plain fetch(url, options) sends GET and everything else is a verb. Writing method anyway is refused with a message that names the verb to use. A program is free to name its own value fetch, and then the methods are its own.
Every server response receives an x-request-id header with a compact unpadded Base64URL request ID. Access logging is disabled by default: pass { logger: true } to app.listen(...) to write a structured event to stderr without request data. When disabled, the server does not serialize or write an access event. Register app.onResponse(...) in the server setup only when application code needs its own metrics, audit record, tracing bridge, or other response-side work. The callback runs once after the server finishes producing the body or discards it, including a streamed body; it cannot change the response. Import Duration from tyrus:temporal when accessing access.duration.
Quick Start
A minimal REST API with typed responses and validation:
import { createRouter, HttpError, HttpReply, HttpRouter, HttpServer, HttpStatus } from "tyrus:http";
interface TodoItem {
id: i64;
title: string;
done: boolean;
}
interface TodoListResponse {
items: TodoItem[];
total: i32;
}
interface CreateTodoInput {
@minLength(1)
title: string;
}
const app: HttpRouter = createRouter();
let nextId: i64 = 1;
const todos: TodoItem[] = [];
app.get("/todos", {
response: { 200: TodoListResponse },
handler: (request, reply) => {
reply.status(HttpStatus.Ok).send({
items: todos,
total: todos.length as i32,
});
},
});
app.post("/todos", {
response: { 201: TodoItem },
handler: (request, reply) => {
const input: CreateTodoInput = request.body;
const todo: TodoItem = { id: nextId, title: input.title, done: false };
nextId += 1;
todos.push(todo);
reply.status(HttpStatus.Created).send(todo);
},
});
const main = (): void => {
const server = app.listen(3000) onfail {
printError(`${server.code}: ${server.message}`);
};
print(`Server listening on port ${server.port()}`);
};Keep layers separated
API lint rules expect routes to declare routing, controllers to translate HTTP boundaries, services to contain business behavior, and repositories to own direct database access.
