We use cookies to improve your experience.

Cookie Policy
Logo of Lexmount
DocsTemplatesBlogHelp Center
GitHub
Logo of LexmountLexmount Browser

Get started

Lexmount Documentation
Console guide

Browser

Web Fetch

OverviewQuick Start
Common Errors

Web Search

OverviewQuick StartSearch API

Runtime

OverviewQuickstart
Overviewfetchlexmount:env
lexmount:browser
Examples

Help and billing

Capability FAQ
ChangelogContact support
API Reference

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>;
ParameterTypeRequiredDescription
inputstring / URL / RequestYesAn absolute URL or an existing request
initRequestInitNoRequest configuration; supplied fields override corresponding settings in the input request
init.methodstringNoDefaults to GET; GET / HEAD cannot carry a body
init.headersHeadersInitNoA Headers object, string-valued record, or array of [name, value] pairs
init.bodyBodyInit / nullNoA string, Blob / File, ArrayBuffer / ArrayBufferView (including TypedArray and DataView), FormData, URLSearchParams, or byte ReadableStream
init.signalAbortSignal / nullNoCancels waiting for a response or reading its body; no active cancellation by default
init.redirectRequestRedirectNofollow (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:

FieldType / valuesDefault and description
referrerstringabout:client; also accepts an empty string or absolute URL
referrerPolicyReferrerPolicyDefaults 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
integritystringEmpty string; no subresource integrity verification
keepalivebooleanfalse; 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:

PropertyTypeDescription
okbooleanWhether the status is 200–299
statusnumberHTTP status code
statusTextstringStatus text, which can be empty
headersHeadersResponse headers; headers.get(name) returns a string or null; also iterable
urlstringResponse URL
redirectedbooleanWhether automatic redirection occurred
typeResponseTypeResponse type
bodyReadableStream<Uint8Array> / nullA byte stream read on demand; null for bodyless responses such as HEAD
bodyUsedbooleanWhether 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.

MethodFunctionReturn value
response.text()Decode the body as UTF-8Promise<string>
response.json()Parse the body as JSON; invalid JSON rejectsPromise<any>
response.arrayBuffer()Read all original bytesPromise<ArrayBuffer>
response.bytes()Read all bytes as a typed arrayPromise<Uint8Array>
response.blob()Read a binary object with its media typePromise<Blob>
response.formData()Parse a supported form-encoded bodyPromise<FormData>
response.clone()Copy an unused, unlocked response and tee its bodyResponse, 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.

Overview

Web APIs and built-in lexmount modules available in the JavaScript runtime.

lexmount:env

Read the immutable instance environment supplied for this execution.

Table of Contents

fetch(input, init?)
Network scope and request options
Response
Body methods
Cancellation and timeouts

Still need help?Ask on Discord