fetch
Send requests from the cloud runtime, read responses, and cancel network operations.
Global fetch makes requests from the cloud runtime. Use it to call public APIs, upload data, and stream responses without importing a module. For services on a client's own machine or private network, use host.fetch in lexmount:remote.
const response = await fetch('https://example.com');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.text());fetch(input, init?)
Function: sends a request and returns a response once its headers arrive. Reading the body is a separate asynchronous operation.
declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;| Parameter | Type | Required | Description |
|---|---|---|---|
input | string / URL / Request | Yes | An absolute URL or an existing request |
init | RequestInit | No | Request configuration; supplied fields override corresponding settings in the input request |
init.method | string | No | Defaults to GET; GET / HEAD cannot carry a body |
init.headers | HeadersInit | No | A Headers object, string-valued record, or array of [name, value] pairs |
init.body | BodyInit / null | No | A string, Blob / File, ArrayBuffer / ArrayBufferView (including TypedArray and DataView), FormData, URLSearchParams, or byte ReadableStream |
init.signal | AbortSignal / null | No | Cancels waiting for a response or reading its body; no active cancellation by default |
init.redirect | RequestRedirect | No | follow (default), manual, or error |
Return value: Promise<Response>. HTTP 4xx / 5xx responses resolve normally; inspect ok or status. Network, DNS, TLS, or destination validation failures reject the promise. Invalid methods and already-used bodies can also cause TypeError.
For FormData, let the runtime generate a Content-Type containing its boundary. For JSON, use JSON.stringify() and set the appropriate header. Upload ReadableStreams must yield byte chunks.
These RequestInit fields are also accepted, but currently only retained on the request object. They do not implement the corresponding browser cache, cookie, CORS, or integrity facilities:
| Field | Type / values | Default and description |
|---|---|---|
referrer | string | about:client; also accepts an empty string or absolute URL |
referrerPolicy | ReferrerPolicy | Defaults to an empty string; also accepts no-referrer, no-referrer-when-downgrade, same-origin, origin, strict-origin, origin-when-cross-origin, strict-origin-when-cross-origin, and unsafe-url |
mode | 'cors' / 'same-origin' / 'no-cors' | cors; navigate is rejected |
credentials | 'omit' / 'same-origin' / 'include' | same-origin; does not automatically attach login cookies |
cache | 'default' / 'no-store' / 'reload' / 'no-cache' / 'force-cache' / 'only-if-cached' | default; only-if-cached requires same-origin mode |
integrity | string | Empty string; no subresource integrity verification |
keepalive | boolean | false; does not guarantee requests survive task completion |
priority | 'auto' / 'high' / 'low' | auto; no network scheduling priority guarantee |
Network scope and request options
HTTP(S) requests allow public destinations only. DNS results and every redirect target are checked. Loopback, private, and other non-public addresses are rejected. data: and blob: URLs can read inline data or objects in the current environment without HTTP networking.
Server-side requests have no page-relative URL base, browser login Cookie Jar, or browser HTTP cache. Browser-side options such as credentials, mode, and cache do not establish those facilities. Set authentication headers explicitly. Host proxies and certificate trust are managed by the platform; application environment variables cannot reconfigure the request client.
Response
The response returned by fetch() exposes these properties:
| Property | Type | Description |
|---|---|---|
ok | boolean | Whether the status is 200–299 |
status | number | HTTP status code |
statusText | string | Status text, which can be empty |
headers | Headers | Response headers; headers.get(name) returns a string or null; also iterable |
url | string | Response URL |
redirected | boolean | Whether automatic redirection occurred |
type | ResponseType | Response type |
body | ReadableStream<Uint8Array> / null | A byte stream read on demand; null for bodyless responses such as HEAD |
bodyUsed | boolean | Whether body consumption has started |
Body methods
These methods take no arguments. Except for clone(), each consumes the whole body and returns a promise. A body can be consumed only once.
| Method | Function | Return value |
|---|---|---|
response.text() | Decode the body as UTF-8 | Promise<string> |
response.json() | Parse the body as JSON; invalid JSON rejects | Promise<any> |
response.arrayBuffer() | Read all original bytes | Promise<ArrayBuffer> |
response.bytes() | Read all bytes as a typed array | Promise<Uint8Array> |
response.blob() | Read a binary object with its media type | Promise<Blob> |
response.formData() | Parse a supported form-encoded body | Promise<FormData> |
response.clone() | Copy an unused, unlocked response and tee its body | Response, returned synchronously |
For streaming reads, use response.body.getReader() and release the reader lock afterward. If you do not need the body, call await response.body?.cancel(); cancel through the reader if it holds the lock. Full-body reads require corresponding memory. Consume or cancel both branches of a clone as well.
Cancellation and timeouts
fetch() has no timeoutMs option. Pass AbortSignal.timeout(milliseconds) or call AbortController.abort(reason?). Cancellation affects the request and its response body, rejecting the promise or a pending read.
const response = await fetch('https://example.com', {
signal: AbortSignal.timeout(10000),
});
console.log(await response.text());A timeout signal normally rejects with TimeoutError; a controller without a custom reason uses AbortError. Handle a supplied reason as that value. Task stop or expiry also cleans up network resources. Cancellation cannot undo an operation already performed by the destination service.
For serving HTTP with a default export, see the public HTTP example.
