Skip to content

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 ​

tyrus
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 ​

ItemSignaturePurpose
createRouter() => HttpRouterCreates a native HTTP router.
API FlowComplete User API exampleFollows the main, Model, schemas, routes, controllers, services, and repository in one SQLite-backed flow.
OpenAPI / Swaggerapp.docs(options)Generates the OpenAPI document and serves the Swagger UI.
Automatic route registrationDiscovers route modules in src/routes/ without a manual registry.
listenapp.listen(port, options?)Starts the server and returns Result<HttpServer, HttpError>. The runtime keeps it alive after main returns.
HttpStatusenum HttpStatusNamed HTTP status codes.
HttpReplytype HttpReply<T>Typed reply API for controllers.
StreamBodytype StreamBodyOpt-in bounded byte stream for a route body or response.
HttpRoutertype HttpRouterNative router returned by createRouter.
onResponse(hook: (access: HttpAccessLog) => void) => voidRegisters an opt-in server-wide response observer.
HttpAccessLoginterface HttpAccessLogImmutable metadata for one completed response.
HttpRequestinterface HttpRequestRaw request available to pre-handlers and raw routes.
HttpResponseinterface HttpResponseRaw response used by pre-handlers and raw routes.
HttpCacheOptionsinterface HttpCacheOptionsETag configuration passed through HttpReplyOptions.
HttpReplyOptionsinterface HttpReplyOptionsOptional response metadata passed as the second reply.send argument.
CorsOptionsinterface CorsOptionsComplete configuration passed to app.cors(...).
CsrfOptionsinterface CsrfOptionsDouble-submit cookie and header names passed to app.csrf(...).
CookieOptionsinterface CookieOptionsOptional attributes passed to reply.setCookie(...).
HttpCookieinterface HttpCookieOne cookie of reply.setCookies([...]): name, value, and optional options.
ServerOptionsinterface ServerOptionsHost, limits, lifecycle settings, optional access logging, and TLS passed to app.listen(...).
HttpErrorinterface HttpErrorRecoverable startup failure returned by app.listen(...), with a stable code and a readable message.
HttpServertype HttpServerRunning server returned by app.listen(...), with port() and close().
WebSockettype WebSocketAn open WebSocket connection, with stream(), receive(), sendText(text), sendBytes(data), close(), protocol() and closeCode().
WebSocketMessageinterface WebSocketMessageOne 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.
HttpClientResponsetype HttpClientResponseThe answer a fetch got, with status(), ok(), header(name), text(), bytes(), json<T>() and close().
HttpClientStreamResponsetype HttpClientStreamResponseThe head of a fetch.stream(...) response, with stream() for its progressive body.
FetchOptionsinterface FetchOptionsHeaders, text or streamed body, timeout, body limit, redirect count and response decompression for a fetch.
FetchPolicyOptionsinterface FetchPolicyOptionsWhere fetch may go, passed to app.fetchPolicy(...).
HttpHeaderinterface HttpHeaderOne 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.

tyrus
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:

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